Home | History | Annotate | Line # | Download | only in dev
fd.c revision 1.89.2.1
      1 /*	$NetBSD: fd.c,v 1.89.2.1 2014/08/10 06:53:49 tls 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.89.2.1 2014/08/10 06:53:49 tls 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 	switch (cmd) {
    577 	case DIOCSBAD:
    578 		return(EINVAL);
    579 	case DIOCSRETRIES:
    580 		if (*(int *)addr < 0)
    581 			return(EINVAL);
    582 		sc->retries = *(int *)addr;
    583 		return(0);
    584 	case DIOCSSTEP:
    585 		if (*(int *)addr < FDSTEPDELAY)
    586 			return(EINVAL);
    587 		sc->dkdev.dk_label->d_trkseek = sc->stepdelay = *(int *)addr;
    588 		return(0);
    589 	case DIOCGDINFO:
    590 		*(struct disklabel *)addr = *(sc->dkdev.dk_label);
    591 		return(0);
    592 	case DIOCGPART:
    593 		((struct partinfo *)addr)->disklab = sc->dkdev.dk_label;
    594 		((struct partinfo *)addr)->part =
    595 		    &sc->dkdev.dk_label->d_partitions[FDPART(dev)];
    596 		return(0);
    597 	case DIOCSDINFO:
    598 		if ((flag & FWRITE) == 0)
    599 			return(EBADF);
    600 		return(fdsetdisklabel(sc, (struct disklabel *)addr));
    601 	case DIOCWDINFO:
    602 		if ((flag & FWRITE) == 0)
    603 			return(EBADF);
    604 		if ((error = fdsetdisklabel(sc, (struct disklabel *)addr)) != 0)
    605 			return(error);
    606 		wlab = sc->wlabel;
    607 		sc->wlabel = 1;
    608 		error = fdputdisklabel(sc, dev);
    609 		sc->wlabel = wlab;
    610 		return(error);
    611 	case DIOCWLABEL:
    612 		if ((flag & FWRITE) == 0)
    613 			return(EBADF);
    614 		sc->wlabel = *(int *)addr;
    615 		return(0);
    616 	case DIOCGDEFLABEL:
    617 		fdgetdefaultlabel(sc, (struct disklabel *)addr, FDPART(dev));
    618 		return(0);
    619 	default:
    620 		return(ENOTTY);
    621 	}
    622 }
    623 
    624 int
    625 fdread(dev_t dev, struct uio *uio, int flags)
    626 {
    627 	return (physio(fdstrategy, NULL, dev, B_READ, fdminphys, uio));
    628 }
    629 
    630 int
    631 fdwrite(dev_t dev, struct uio *uio, int flags)
    632 {
    633 	return (physio(fdstrategy, NULL, dev, B_WRITE, fdminphys, uio));
    634 }
    635 
    636 
    637 void
    638 fdintr(int flag)
    639 {
    640 	int s;
    641 
    642 	s = splbio();
    643 	if (fdc_indma)
    644 		fddmadone(fdc_indma, 0);
    645 	splx(s);
    646 }
    647 
    648 void
    649 fdidxintr(void)
    650 {
    651 	if (fdc_indma && fdc_dmalen) {
    652 		/*
    653 		 * turn off intr and start actual dma
    654 		 */
    655 		ciab.icr = CIA_ICR_FLG;
    656 		FDDMASTART(fdc_dmalen, fdc_dmawrite);
    657 		fdc_dmalen = 0;
    658 	}
    659 }
    660 
    661 void
    662 fdstrategy(struct buf *bp)
    663 {
    664 	struct fd_softc *sc;
    665 	int unit, s;
    666 
    667 	unit = FDUNIT(bp->b_dev);
    668 	sc = getsoftc(fd_cd, unit);
    669 
    670 #ifdef FDDEBUG
    671 	printf("fdstrategy: %p\n", bp);
    672 #endif
    673 	/*
    674 	 * check for valid partition and bounds
    675 	 */
    676 	if ((sc->flags & FDF_HAVELABEL) == 0) {
    677 		bp->b_error = EIO;
    678 		goto done;
    679 	}
    680 	if (bounds_check_with_label(&sc->dkdev, bp, sc->wlabel) <= 0)
    681 		goto done;
    682 
    683 	/*
    684 	 * trans count of zero or bounds check indicates io is done
    685 	 * we are done.
    686 	 */
    687 	if (bp->b_bcount == 0)
    688 		goto done;
    689 
    690 	bp->b_rawblkno = bp->b_blkno;
    691 
    692 	/*
    693 	 * queue the buf and kick the low level code
    694 	 */
    695 	s = splbio();
    696 	bufq_put(sc->bufq, bp);
    697 	fdstart(sc);
    698 	splx(s);
    699 	return;
    700 done:
    701 	bp->b_resid = bp->b_bcount;
    702 	biodone(bp);
    703 }
    704 
    705 /*
    706  * make sure disk is loaded and label is up-to-date.
    707  */
    708 int
    709 fdloaddisk(struct fd_softc *sc)
    710 {
    711 	/*
    712 	 * if diskchange is low step drive to 0 then up one then to zero.
    713 	 */
    714 	fdselunit(sc);			/* make sure the unit is selected */
    715 	if (FDTESTC(FDB_CHANGED)) {
    716 		fdsetpos(sc, 0, 0);
    717 		sc->cachetrk = -1;		/* invalidate the cache */
    718 		sc->flags &= ~FDF_HAVELABEL;
    719 		fdsetpos(sc, FDNHEADS, 0);
    720 		fdsetpos(sc, 0, 0);
    721 		if (FDTESTC(FDB_CHANGED)) {
    722 			fdmotoroff(sc);
    723 			FDDESELECT(sc->unitmask);
    724 			return(ENXIO);
    725 		}
    726 	}
    727 	FDDESELECT(sc->unitmask);
    728 	fdmotoroff(sc);
    729 	sc->type = fdcgetfdtype(sc->hwunit);
    730 	if (sc->type == NULL)
    731 		return(ENXIO);
    732 	if (sc->openpart == FDMSDOSPART)
    733 		sc->nsectors = sc->type->msdos_nsectors;
    734 	else
    735 		sc->nsectors = sc->type->amiga_nsectors;
    736 	return(0);
    737 }
    738 
    739 void
    740 fdgetdefaultlabel(struct fd_softc *sc, struct disklabel *lp, int part)
    741 /* (variable part) XXX ick */
    742 {
    743 
    744 	memset(lp, 0, sizeof(struct disklabel));
    745 	lp->d_secsize = FDSECSIZE;
    746 	lp->d_ntracks = FDNHEADS;
    747 	lp->d_ncylinders = sc->type->ncylinders;
    748 	lp->d_nsectors = sc->nsectors;
    749 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
    750 	lp->d_type = DTYPE_FLOPPY;
    751 	lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
    752 	lp->d_rpm = 300; 		/* good guess I suppose. */
    753 	lp->d_interleave = 1;		/* should change when adding msdos */
    754 	sc->stepdelay = lp->d_trkseek = FDSTEPDELAY;
    755 	lp->d_bbsize = 0;
    756 	lp->d_sbsize = 0;
    757 	lp->d_partitions[part].p_size = lp->d_secperunit;
    758 	lp->d_partitions[part].p_fstype = FS_UNUSED;
    759 	lp->d_partitions[part].p_fsize = 1024;
    760 	lp->d_partitions[part].p_frag = 8;
    761 	lp->d_partitions[part].p_cpg = 2;	/* adosfs: reserved blocks */
    762 	lp->d_npartitions = part + 1;
    763 	lp->d_magic = lp->d_magic2 = DISKMAGIC;
    764 	lp->d_checksum = dkcksum(lp);
    765 }
    766 
    767 /*
    768  * read disk label, if present otherwise create one
    769  * return a new label if raw part and none found, otherwise err.
    770  */
    771 int
    772 fdgetdisklabel(struct fd_softc *sc, dev_t dev)
    773 {
    774 	struct disklabel *lp, *dlp;
    775 	struct cpu_disklabel *clp;
    776 	struct buf *bp;
    777 	int error, part;
    778 
    779 	if (sc->flags & FDF_HAVELABEL &&
    780 	    sc->dkdev.dk_label->d_npartitions == (FDPART(dev) + 1))
    781 		return(0);
    782 #ifdef FDDEBUG
    783 	printf("fdgetdisklabel()\n");
    784 #endif
    785 	part = FDPART(dev);
    786 	lp = sc->dkdev.dk_label;
    787 	clp =  sc->dkdev.dk_cpulabel;
    788 	memset(lp, 0, sizeof(struct disklabel));
    789 	memset(clp, 0, sizeof(struct cpu_disklabel));
    790 
    791 	lp->d_secsize = FDSECSIZE;
    792 	lp->d_ntracks = FDNHEADS;
    793 	lp->d_ncylinders = sc->type->ncylinders;
    794 	lp->d_nsectors = sc->nsectors;
    795 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
    796 	lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
    797 	lp->d_npartitions = part + 1;
    798 	lp->d_partitions[part].p_size = lp->d_secperunit;
    799 	lp->d_partitions[part].p_fstype = FS_UNUSED;
    800 	lp->d_partitions[part].p_fsize = 1024;
    801 	lp->d_partitions[part].p_frag = 8;
    802 	lp->d_partitions[part].p_cpg = 2;	/* for adosfs: reserved blks */
    803 
    804 	sc->flags |= FDF_HAVELABEL;
    805 
    806 	bp = (void *)geteblk((int)lp->d_secsize);
    807 	bp->b_dev = dev;
    808 	bp->b_blkno = 0;
    809 	bp->b_cylinder = 0;
    810 	bp->b_bcount = FDSECSIZE;
    811 	bp->b_flags |= B_READ;
    812 	fdstrategy(bp);
    813 	if ((error = biowait(bp)) != 0)
    814 		goto nolabel;
    815 	dlp = (struct disklabel *)((char*)bp->b_data + LABELOFFSET);
    816 	if (dlp->d_magic != DISKMAGIC || dlp->d_magic2 != DISKMAGIC ||
    817 	    dkcksum(dlp)) {
    818 		error = EINVAL;
    819 		goto nolabel;
    820 	}
    821 	memcpy(lp, dlp, sizeof(struct disklabel));
    822 	if (lp->d_trkseek > FDSTEPDELAY)
    823 		sc->stepdelay = lp->d_trkseek;
    824 	brelse(bp, 0);
    825 	return(0);
    826 nolabel:
    827 	fdgetdefaultlabel(sc, lp, part);
    828 	brelse(bp, 0);
    829 	return(0);
    830 }
    831 
    832 /*
    833  * set the incore copy of this units disklabel
    834  */
    835 int
    836 fdsetdisklabel(struct fd_softc *sc, struct disklabel *lp)
    837 {
    838 	struct disklabel *clp;
    839 	struct partition *pp;
    840 
    841 	/*
    842 	 * must have at least opened raw unit to fetch the
    843 	 * raw_part stuff.
    844 	 */
    845 	if ((sc->flags & FDF_HAVELABEL) == 0)
    846 		return(EINVAL);
    847 	clp = sc->dkdev.dk_label;
    848 	/*
    849 	 * make sure things check out and we only have one valid
    850 	 * partition
    851 	 */
    852 #ifdef FDDEBUG
    853 	printf("fdsetdisklabel\n");
    854 #endif
    855 	if (lp->d_secsize != FDSECSIZE ||
    856 	    lp->d_nsectors != clp->d_nsectors ||
    857 	    lp->d_ntracks != FDNHEADS ||
    858 	    lp->d_ncylinders != clp->d_ncylinders ||
    859 	    lp->d_secpercyl != clp->d_secpercyl ||
    860 	    lp->d_secperunit != clp->d_secperunit ||
    861 	    lp->d_magic != DISKMAGIC ||
    862 	    lp->d_magic2 != DISKMAGIC ||
    863 	    lp->d_npartitions == 0 ||
    864 	    lp->d_npartitions > FDMAXPARTS ||
    865 	    (lp->d_partitions[0].p_offset && lp->d_partitions[1].p_offset) ||
    866 	    dkcksum(lp))
    867 		return(EINVAL);
    868 	/*
    869 	 * if any partitions are present make sure they
    870 	 * represent the currently open type
    871 	 */
    872 	if ((pp = &lp->d_partitions[0])->p_size) {
    873 		if ((pp = &lp->d_partitions[1])->p_size == 0)
    874 			goto done;
    875 		else if (sc->openpart != 1)
    876 			return(EINVAL);
    877 	} else if (sc->openpart != 0)
    878 		return(EINVAL);
    879 	/*
    880 	 * make sure selected partition is within bounds
    881 	 * XXX on the second check, its to handle a bug in
    882 	 * XXX the cluster routines as they require mutliples
    883 	 * XXX of PAGE_SIZE currently
    884 	 */
    885 	if ((pp->p_offset + pp->p_size >= lp->d_secperunit) ||
    886 	    (pp->p_frag * pp->p_fsize % PAGE_SIZE))
    887 		return(EINVAL);
    888 done:
    889 	memcpy(clp, lp, sizeof(struct disklabel));
    890 	return(0);
    891 }
    892 
    893 /*
    894  * write out the incore copy of this units disklabel
    895  */
    896 int
    897 fdputdisklabel(struct fd_softc *sc, dev_t dev)
    898 {
    899 	struct disklabel *lp, *dlp;
    900 	struct buf *bp;
    901 	int error;
    902 
    903 	if ((sc->flags & FDF_HAVELABEL) == 0)
    904 		return(EBADF);
    905 #ifdef FDDEBUG
    906 	printf("fdputdisklabel\n");
    907 #endif
    908 	/*
    909 	 * get buf and read in sector 0
    910 	 */
    911 	lp = sc->dkdev.dk_label;
    912 	bp = geteblk((int)lp->d_secsize);
    913 	bp->b_dev = FDMAKEDEV(major(dev), FDUNIT(dev), RAW_PART);
    914 	bp->b_blkno = 0;
    915 	bp->b_cylinder = 0;
    916 	bp->b_bcount = FDSECSIZE;
    917 	bp->b_flags |= B_READ;
    918 	fdstrategy(bp);
    919 	if ((error = biowait(bp)) != 0)
    920 		goto done;
    921 	/*
    922 	 * copy disklabel to buf and write it out synchronous
    923 	 */
    924 	dlp = (struct disklabel *)((char*)bp->b_data + LABELOFFSET);
    925 	memcpy(dlp, lp, sizeof(struct disklabel));
    926 	bp->b_blkno = 0;
    927 	bp->b_cylinder = 0;
    928 	bp->b_flags &= ~(B_READ);
    929 	bp->b_oflags &= ~(BO_DONE);
    930 	bp->b_flags |= B_WRITE;
    931 	fdstrategy(bp);
    932 	error = biowait(bp);
    933 done:
    934 	brelse(bp, 0);
    935 	return(error);
    936 }
    937 
    938 /*
    939  * figure out drive type or NULL if none.
    940  */
    941 struct fdtype *
    942 fdcgetfdtype(int unit)
    943 {
    944 	struct fdtype *ftp;
    945 	u_long id, idb;
    946 	int cnt, umask;
    947 
    948 	id = 0;
    949 	umask = 1 << (3 + unit);
    950 
    951 	FDDESELECT(FDCUNITMASK);
    952 
    953 	FDSETMOTOR(1);
    954 	delay(1);
    955 	FDSELECT(umask);
    956 	delay(1);
    957 	FDDESELECT(umask);
    958 
    959 	FDSETMOTOR(0);
    960 	delay(1);
    961 	FDSELECT(umask);
    962 	delay(1);
    963 	FDDESELECT(umask);
    964 
    965 	for (idb = 0x80000000; idb; idb >>= 1) {
    966 		FDSELECT(umask);
    967 		delay(1);
    968 		if (FDTESTC(FDB_READY) == 0)
    969 			id |= idb;
    970 		FDDESELECT(umask);
    971 		delay(1);
    972 	}
    973 #ifdef FDDEBUG
    974 	printf("fdcgettype unit %d id 0x%lx\n", unit, id);
    975 #endif
    976 
    977 	for (cnt = 0, ftp = fdtype; cnt < nfdtype; ftp++, cnt++)
    978 		if (ftp->driveid == id)
    979 			return(ftp);
    980 	/*
    981 	 * 3.5dd's at unit 0 do not always return id.
    982 	 */
    983 	if (unit == 0)
    984 		return(fdtype);
    985 	return(NULL);
    986 }
    987 
    988 /*
    989  * turn motor off if possible otherwise mark as needed and will be done
    990  * later.
    991  */
    992 void
    993 fdmotoroff(void *arg)
    994 {
    995 	struct fd_softc *sc;
    996 	int s;
    997 
    998 	sc = arg;
    999 	s = splbio();
   1000 
   1001 #ifdef FDDEBUG
   1002 	printf("fdmotoroff: unit %d\n", sc->hwunit);
   1003 #endif
   1004 	if ((sc->flags & FDF_MOTORON) == 0)
   1005 		goto done;
   1006 	/*
   1007 	 * if we have a timeout on a DMA operation let fddmadone()
   1008 	 * deal with it.
   1009 	 */
   1010 	if (fdc_indma == sc) {
   1011 		fddmadone(sc, 1);
   1012 		goto done;
   1013 	}
   1014 #ifdef FDDEBUG
   1015 	printf(" motor was on, turning off\n");
   1016 #endif
   1017 
   1018 	/*
   1019 	 * flush cache if needed
   1020 	 */
   1021 	if (sc->flags & FDF_DIRTY) {
   1022 		sc->flags |= FDF_JUSTFLUSH | FDF_MOTOROFF;
   1023 #ifdef FDDEBUG
   1024 		printf("  flushing dirty buffer first\n");
   1025 #endif
   1026 		/*
   1027 		 * if DMA'ing done for now, fddone() will call us again
   1028 		 */
   1029 		if (fdc_indma)
   1030 			goto done;
   1031 		fddmastart(sc, sc->cachetrk);
   1032 		goto done;
   1033 	}
   1034 
   1035 	/*
   1036 	 * if controller is busy just schedule us to be called back
   1037 	 */
   1038 	if (fdc_indma) {
   1039 		/*
   1040 		 * someone else has the controller now
   1041 		 * just set flag and let fddone() call us again.
   1042 		 */
   1043 		sc->flags |= FDF_MOTOROFF;
   1044 		goto done;
   1045 	}
   1046 
   1047 #ifdef FDDEBUG
   1048 	printf("  hw turning unit off\n");
   1049 #endif
   1050 
   1051 	sc->flags &= ~(FDF_MOTORON | FDF_MOTOROFF);
   1052 	FDDESELECT(FDCUNITMASK);
   1053 	FDSETMOTOR(0);
   1054 	delay(1);
   1055 	FDSELECT(sc->unitmask);
   1056 	delay(4);
   1057 	FDDESELECT(sc->unitmask);
   1058 	delay(1);
   1059 	if (sc->flags & FDF_WMOTOROFF)
   1060 		wakeup(fdmotoroff);
   1061 done:
   1062 	splx(s);
   1063 }
   1064 
   1065 /*
   1066  * select drive seek to track exit with motor on.
   1067  * fdsetpos(x, 0, 0) does calibrates the drive.
   1068  */
   1069 void
   1070 fdsetpos(struct fd_softc *sc, int trk, int towrite)
   1071 {
   1072 	int nstep, sdir, ondly, ncyl, nside;
   1073 
   1074 	FDDESELECT(FDCUNITMASK);
   1075 	FDSETMOTOR(1);
   1076 	delay(1);
   1077 	FDSELECT(sc->unitmask);
   1078 	delay(1);
   1079 	if ((sc->flags & FDF_MOTORON) == 0) {
   1080 		ondly = 0;
   1081 		while (FDTESTC(FDB_READY) == 0) {
   1082 			delay(1000);
   1083 			if (++ondly >= 1000)
   1084 				break;
   1085 		}
   1086 	}
   1087 	sc->flags |= FDF_MOTORON;
   1088 
   1089 	ncyl = trk / FDNHEADS;
   1090 	nside = trk % FDNHEADS;
   1091 
   1092 	if (sc->curcyl == ncyl && fdc_side == nside)
   1093 		return;
   1094 
   1095 	if (towrite)
   1096 		sc->flags |= FDF_WRITEWAIT;
   1097 
   1098 #ifdef FDDEBUG
   1099 	printf("fdsetpos: cyl %d head %d towrite %d\n", trk / FDNHEADS,
   1100 	    trk % FDNHEADS, towrite);
   1101 #endif
   1102 	nstep = ncyl - sc->curcyl;
   1103 	if (nstep) {
   1104 		/*
   1105 		 * figure direction
   1106 		 */
   1107 		if (nstep > 0 && ncyl != 0) {
   1108 			sdir = FDSTEPIN;
   1109 			FDSETDIR(1);
   1110 		} else {
   1111 			nstep = -nstep;
   1112 			sdir = FDSTEPOUT;
   1113 			FDSETDIR(0);
   1114 		}
   1115 		if (ncyl == 0) {
   1116 			/*
   1117 			 * either just want cylinder 0 or doing
   1118 			 * a calibrate.
   1119 			 */
   1120 			nstep = 256;
   1121 			while (FDTESTC(FDB_CYLZERO) == 0 && nstep--) {
   1122 				FDSTEP;
   1123 				delay(sc->stepdelay);
   1124 			}
   1125 			if (nstep < 0)
   1126 				sc->flags |= FDF_NOTRACK0;
   1127 		} else {
   1128 			/*
   1129 			 * step the needed amount amount.
   1130 			 */
   1131 			while (nstep--) {
   1132 				FDSTEP;
   1133 				delay(sc->stepdelay);
   1134 			}
   1135 		}
   1136 		/*
   1137 		 * if switched directions
   1138 		 * allow drive to settle.
   1139 		 */
   1140 		if (sc->pstepdir != sdir)
   1141 			delay(FDSETTLEDELAY);
   1142 		sc->pstepdir = sdir;
   1143 		sc->curcyl = ncyl;
   1144 	}
   1145 	if (nside == fdc_side)
   1146 		return;
   1147 	/*
   1148 	 * select side
   1149 	 */
   1150 	fdc_side = nside;
   1151 	FDSETHEAD(nside);
   1152 	delay(FDPRESIDEDELAY);
   1153 }
   1154 
   1155 void
   1156 fdselunit(struct fd_softc *sc)
   1157 {
   1158 	FDDESELECT(FDCUNITMASK);		/* deselect all */
   1159 	FDSETMOTOR(sc->flags & FDF_MOTORON);	/* set motor to unit's state */
   1160 	delay(1);
   1161 	FDSELECT(sc->unitmask);			/* select unit */
   1162 	delay(1);
   1163 }
   1164 
   1165 /*
   1166  * process next buf on device queue.
   1167  * normall sequence of events:
   1168  * fdstart() -> fddmastart();
   1169  * fdidxintr();
   1170  * fdintr() -> fddmadone() -> fddone();
   1171  * if the track is in the cache then fdstart() will short-circuit
   1172  * to fddone() else if the track cache is dirty it will flush.  If
   1173  * the buf is not an entire track it will cache the requested track.
   1174  */
   1175 void
   1176 fdstart(struct fd_softc *sc)
   1177 {
   1178 	int trk, error, write;
   1179 	struct buf *bp, *dp;
   1180 	int changed;
   1181 
   1182 #ifdef FDDEBUG
   1183 	printf("fdstart: unit %d\n", sc->hwunit);
   1184 #endif
   1185 
   1186 	/*
   1187 	 * if DMA'ing just return. we must have been called from fdstartegy.
   1188 	 */
   1189 	if (fdc_indma)
   1190 		return;
   1191 
   1192 	/*
   1193 	 * get next buf if there.
   1194 	 */
   1195 	dp = &sc->curbuf;
   1196 	if ((bp = bufq_peek(sc->bufq)) == NULL) {
   1197 #ifdef FDDEBUG
   1198 		printf("  nothing to do\n");
   1199 #endif
   1200 		return;
   1201 	}
   1202 
   1203 	/*
   1204 	 * Mark us as busy now, in case fddone() gets called in one
   1205 	 * of the cases below.
   1206 	 */
   1207 	disk_busy(&sc->dkdev);
   1208 
   1209 	/*
   1210 	 * make sure same disk is loaded
   1211 	 */
   1212 	fdselunit(sc);
   1213 	changed = FDTESTC(FDB_CHANGED);
   1214 	FDDESELECT(sc->unitmask);
   1215 	if (changed) {
   1216 		/*
   1217 		 * disk missing, invalidate all future io on
   1218 		 * this unit until re-open()'ed also invalidate
   1219 		 * all current io
   1220 		 */
   1221 printf("fdstart: disk changed\n");
   1222 #ifdef FDDEBUG
   1223 		printf("  disk was removed invalidating all io\n");
   1224 #endif
   1225 		sc->flags &= ~FDF_HAVELABEL;
   1226 		for (;;) {
   1227 			bp = bufq_get(sc->bufq);
   1228 			bp->b_error = EIO;
   1229 			if (bufq_peek(sc->bufq) == NULL)
   1230 				break;
   1231 			biodone(bp);
   1232 		}
   1233 		/*
   1234 		 * do fddone() on last buf to allow other units to start.
   1235 		 */
   1236 		bufq_put(sc->bufq, bp);
   1237 		fddone(sc);
   1238 		return;
   1239 	}
   1240 
   1241 	/*
   1242 	 * we have a valid buf, setup our local version
   1243 	 * we use this count to allow reading over multiple tracks.
   1244 	 * into a single buffer
   1245 	 */
   1246 	dp->b_bcount = bp->b_bcount;
   1247 	dp->b_blkno = bp->b_blkno;
   1248 	dp->b_data = bp->b_data;
   1249 	dp->b_flags = bp->b_flags;
   1250 	dp->b_resid = 0;
   1251 
   1252 	if (bp->b_flags & B_READ)
   1253 		write = 0;
   1254 	else if (FDTESTC(FDB_PROTECT) == 0)
   1255 		write = 1;
   1256 	else {
   1257 		error = EPERM;
   1258 		goto done;
   1259 	}
   1260 
   1261 	/*
   1262 	 * figure trk given blkno
   1263 	 */
   1264 	trk = bp->b_blkno / sc->nsectors;
   1265 
   1266 	/*
   1267 	 * check to see if same as currently cached track
   1268 	 * if so we need to do no DMA read.
   1269 	 */
   1270 	if (trk == sc->cachetrk) {
   1271 		fddone(sc);
   1272 		return;
   1273 	}
   1274 
   1275 	/*
   1276 	 * if we will be overwriting the entire cache, don't bother to
   1277 	 * fetch it.
   1278 	 */
   1279 	if (bp->b_bcount == (sc->nsectors * FDSECSIZE) && write &&
   1280 	    bp->b_blkno % sc->nsectors == 0) {
   1281 		if (sc->flags & FDF_DIRTY)
   1282 			sc->flags |= FDF_JUSTFLUSH;
   1283 		else {
   1284 			sc->cachetrk = trk;
   1285 			fddone(sc);
   1286 			return;
   1287 		}
   1288 	}
   1289 
   1290 	/*
   1291 	 * start DMA read of `trk'
   1292 	 */
   1293 	fddmastart(sc, trk);
   1294 	return;
   1295 done:
   1296 	bp->b_error = error;
   1297 	fddone(sc);
   1298 }
   1299 
   1300 /*
   1301  * continue a started operation on next track. always begin at
   1302  * sector 0 on the next track.
   1303  */
   1304 void
   1305 fdcont(struct fd_softc *sc)
   1306 {
   1307 	struct buf *dp, *bp;
   1308 	int trk, write;
   1309 
   1310 	dp = &sc->curbuf;
   1311 	bp = bufq_peek(sc->bufq);
   1312 	dp->b_data = (char*)dp->b_data + (dp->b_bcount - bp->b_resid);
   1313 	dp->b_blkno += (dp->b_bcount - bp->b_resid) / FDSECSIZE;
   1314 	dp->b_bcount = bp->b_resid;
   1315 
   1316 	/*
   1317 	 * figure trk given blkno
   1318 	 */
   1319 	trk = dp->b_blkno / sc->nsectors;
   1320 #ifdef DEBUG
   1321 	if (trk != sc->cachetrk + 1 || dp->b_blkno % sc->nsectors != 0)
   1322 		panic("fdcont: confused");
   1323 #endif
   1324 	if (dp->b_flags & B_READ)
   1325 		write = 0;
   1326 	else
   1327 		write = 1;
   1328 	/*
   1329 	 * if we will be overwriting the entire cache, don't bother to
   1330 	 * fetch it.
   1331 	 */
   1332 	if (dp->b_bcount == (sc->nsectors * FDSECSIZE) && write) {
   1333 		if (sc->flags & FDF_DIRTY)
   1334 			sc->flags |= FDF_JUSTFLUSH;
   1335 		else {
   1336 			sc->cachetrk = trk;
   1337 			fddone(sc);
   1338 			return;
   1339 		}
   1340 	}
   1341 	/*
   1342 	 * start DMA read of `trk'
   1343 	 */
   1344 	fddmastart(sc, trk);
   1345 	return;
   1346 }
   1347 
   1348 void
   1349 fddmastart(struct fd_softc *sc, int trk)
   1350 {
   1351 	int adkmask, ndmaw, write, dmatrk;
   1352 
   1353 #ifdef FDDEBUG
   1354 	printf("fddmastart: unit %d cyl %d head %d", sc->hwunit,
   1355 	    trk / FDNHEADS, trk % FDNHEADS);
   1356 #endif
   1357 	/*
   1358 	 * flush the cached track if dirty else read requested track.
   1359 	 */
   1360 	if (sc->flags & FDF_DIRTY) {
   1361 		fdcachetoraw(sc);
   1362 		ndmaw = sc->type->nwritew;
   1363 		dmatrk = sc->cachetrk;
   1364 		write = 1;
   1365 	} else {
   1366 		ndmaw = sc->type->nreadw;
   1367 		dmatrk = trk;
   1368 		write = 0;
   1369 	}
   1370 
   1371 #ifdef FDDEBUG
   1372 	printf(" %s", write ? " flushing cache\n" : " loading cache\n");
   1373 #endif
   1374 	sc->cachetrk = trk;
   1375 	fdc_indma = sc;
   1376 	fdsetpos(sc, dmatrk, write);
   1377 
   1378 	/*
   1379 	 * setup dma stuff
   1380 	 */
   1381 	if (write == 0) {
   1382 		custom.adkcon = ADKF_MSBSYNC;
   1383 		custom.adkcon = ADKF_SETCLR | ADKF_WORDSYNC | ADKF_FAST;
   1384 		custom.dsksync = FDMFMSYNC;
   1385 	} else {
   1386 		custom.adkcon = ADKF_PRECOMP1 | ADKF_PRECOMP0 | ADKF_WORDSYNC |
   1387 		    ADKF_MSBSYNC;
   1388 		adkmask = ADKF_SETCLR | ADKF_FAST | ADKF_MFMPREC;
   1389 		if (dmatrk >= sc->type->precomp[0])
   1390 			adkmask |= ADKF_PRECOMP0;
   1391 		if (dmatrk >= sc->type->precomp[1])
   1392 			adkmask |= ADKF_PRECOMP1;
   1393 		custom.adkcon = adkmask;
   1394 	}
   1395 	custom.dskpt = (u_char *)kvtop(fdc_dmap);
   1396 
   1397 	/*
   1398 	 * If writing an MSDOS track, activate disk index pulse
   1399 	 * interrupt, DMA will be started in the intr routine fdidxintr()
   1400 	 * Otherwise, start the DMA here.
   1401 	 */
   1402 	if (write && sc->openpart == FDMSDOSPART) {
   1403 		fdc_dmalen = ndmaw;
   1404 		fdc_dmawrite = write;
   1405 		ciab.icr = CIA_ICR_IR_SC | CIA_ICR_FLG;
   1406 	} else {
   1407 		FDDMASTART(ndmaw, write);
   1408 		fdc_dmalen = 0;
   1409 	}
   1410 
   1411 #ifdef FDDEBUG
   1412 	printf("  DMA started\n");
   1413 #endif
   1414 }
   1415 
   1416 /*
   1417  * recalibrate the drive
   1418  */
   1419 void
   1420 fdcalibrate(void *arg)
   1421 {
   1422 	struct fd_softc *sc;
   1423 	static int loopcnt;
   1424 
   1425 	sc = arg;
   1426 
   1427 	if (loopcnt == 0) {
   1428 		/*
   1429 		 * seek cyl 0
   1430 		 */
   1431 		fdc_indma = sc;
   1432 		sc->stepdelay += 900;
   1433 		if (sc->cachetrk > 1)
   1434 			fdsetpos(sc, sc->cachetrk % FDNHEADS, 0);
   1435 		sc->stepdelay -= 900;
   1436 	}
   1437 	if (loopcnt++ & 1)
   1438 		fdsetpos(sc, sc->cachetrk, 0);
   1439 	else
   1440 		fdsetpos(sc, sc->cachetrk + FDNHEADS, 0);
   1441 	/*
   1442 	 * trk++, trk, trk++, trk, trk++, trk, trk++, trk and DMA
   1443 	 */
   1444 	if (loopcnt < 8)
   1445 		callout_reset(&sc->calibrate_ch, hz / 8, fdcalibrate, sc);
   1446 	else {
   1447 		loopcnt = 0;
   1448 		fdc_indma = NULL;
   1449 		callout_reset(&sc->motor_ch, 3 * hz / 2, fdmotoroff, sc);
   1450 		fddmastart(sc, sc->cachetrk);
   1451 	}
   1452 }
   1453 
   1454 void
   1455 fddmadone(struct fd_softc *sc, int timeo)
   1456 {
   1457 #ifdef FDDEBUG
   1458 	printf("fddmadone: unit %d, timeo %d\n", sc->hwunit, timeo);
   1459 #endif
   1460 	fdc_indma = NULL;
   1461 	callout_stop(&sc->motor_ch);
   1462 	FDDMASTOP;
   1463 
   1464 	/*
   1465 	 * guarantee the drive has been at current head and cyl
   1466 	 * for at least FDWRITEDELAY after a write.
   1467 	 */
   1468 	if (sc->flags & FDF_WRITEWAIT) {
   1469 		delay(FDWRITEDELAY);
   1470 		sc->flags &= ~FDF_WRITEWAIT;
   1471 	}
   1472 
   1473 	if ((sc->flags & FDF_MOTOROFF) == 0) {
   1474 		/*
   1475 		 * motor runs for 1.5 seconds after last DMA
   1476 		 */
   1477 		callout_reset(&sc->motor_ch, 3 * hz / 2, fdmotoroff, sc);
   1478 	}
   1479 	if (sc->flags & FDF_DIRTY) {
   1480 		/*
   1481 		 * if buffer dirty, the last DMA cleaned it
   1482 		 */
   1483 		sc->flags &= ~FDF_DIRTY;
   1484 		if (timeo)
   1485 			aprint_error_dev(sc->sc_dev,
   1486 			    "write of track cache timed out.\n");
   1487 		if (sc->flags & FDF_JUSTFLUSH) {
   1488 			sc->flags &= ~FDF_JUSTFLUSH;
   1489 			/*
   1490 			 * we are done DMA'ing
   1491 			 */
   1492 			fddone(sc);
   1493 			return;
   1494 		}
   1495 		/*
   1496 		 * load the cache
   1497 		 */
   1498 		fddmastart(sc, sc->cachetrk);
   1499 		return;
   1500 	}
   1501 #ifdef FDDEBUG
   1502 	else if (sc->flags & FDF_MOTOROFF)
   1503 		panic("fddmadone: FDF_MOTOROFF with no FDF_DIRTY");
   1504 #endif
   1505 
   1506 	/*
   1507 	 * cache loaded decode it into cache buffer
   1508 	 */
   1509 	if (timeo == 0 && fdrawtocache(sc) == 0)
   1510 		sc->retried = 0;
   1511 	else {
   1512 #ifdef FDDEBUG
   1513 		if (timeo)
   1514 			aprint_debug_dev(sc->sc_dev,
   1515 			    "fddmadone: cache load timed out.\n");
   1516 #endif
   1517 		if (sc->retried >= sc->retries) {
   1518 			sc->retried = 0;
   1519 			sc->cachetrk = -1;
   1520 		} else {
   1521 			sc->retried++;
   1522 			/*
   1523 			 * this will be restarted at end of calibrate loop.
   1524 			 */
   1525 			callout_stop(&sc->motor_ch);
   1526 			fdcalibrate(sc);
   1527 			return;
   1528 		}
   1529 	}
   1530 	fddone(sc);
   1531 }
   1532 
   1533 void
   1534 fddone(struct fd_softc *sc)
   1535 {
   1536 	struct buf *dp, *bp;
   1537 	char *data;
   1538 	int sz;
   1539 
   1540 #ifdef FDDEBUG
   1541 	printf("fddone: unit %d\n", sc->hwunit);
   1542 #endif
   1543 	/*
   1544 	 * check to see if unit is just flushing the cache,
   1545 	 * that is we have no io queued.
   1546 	 */
   1547 	if (sc->flags & FDF_MOTOROFF)
   1548 		goto nobuf;
   1549 
   1550 	dp = &sc->curbuf;
   1551 	if ((bp = bufq_peek(sc->bufq)) == NULL)
   1552 		panic ("fddone");
   1553 	/*
   1554 	 * check for an error that may have occurred
   1555 	 * while getting the track.
   1556 	 */
   1557 	if (sc->cachetrk == -1) {
   1558 		sc->retried = 0;
   1559 		bp->b_error = EIO;
   1560 	} else if (bp->b_error == 0) {
   1561 		data = sc->cachep;
   1562 		/*
   1563 		 * get offset of data in track cache and limit
   1564 		 * the copy size to not exceed the cache's end.
   1565 		 */
   1566 		data += (dp->b_blkno % sc->nsectors) * FDSECSIZE;
   1567 		sz = sc->nsectors - dp->b_blkno % sc->nsectors;
   1568 		sz *= FDSECSIZE;
   1569 		sz = min(dp->b_bcount, sz);
   1570 		if (bp->b_flags & B_READ)
   1571 			memcpy(dp->b_data, data, sz);
   1572 		else {
   1573 			memcpy(data, dp->b_data, sz);
   1574 			sc->flags |= FDF_DIRTY;
   1575 		}
   1576 		bp->b_resid = dp->b_bcount - sz;
   1577 		if (bp->b_resid == 0) {
   1578 			bp->b_error = 0;
   1579 		} else {
   1580 			/*
   1581 			 * not done yet need to read next track
   1582 			 */
   1583 			fdcont(sc);
   1584 			return;
   1585 		}
   1586 	}
   1587 	/*
   1588 	 * remove from queue.
   1589 	 */
   1590 	(void)bufq_get(sc->bufq);
   1591 
   1592 	disk_unbusy(&sc->dkdev, (bp->b_bcount - bp->b_resid),
   1593 	    (bp->b_flags & B_READ));
   1594 
   1595 	biodone(bp);
   1596 nobuf:
   1597 	fdfindwork(device_unit(sc->sc_dev));
   1598 }
   1599 
   1600 void
   1601 fdfindwork(int unit)
   1602 {
   1603 	struct fd_softc *ssc, *sc;
   1604 	int i, last;
   1605 
   1606 	/*
   1607 	 * first see if we have any fdopen()'s waiting
   1608 	 */
   1609 	if (fdc_wantwakeup) {
   1610 		wakeup(fdopen);
   1611 		fdc_wantwakeup--;
   1612 		return;
   1613 	}
   1614 
   1615 	/*
   1616 	 * start next available unit, linear search from the next unit
   1617 	 * wrapping and finally this unit.
   1618 	 */
   1619 	last = 0;
   1620 	ssc = NULL;
   1621 	for (i = unit + 1; last == 0; i++) {
   1622 		if (i == unit)
   1623 			last = 1;
   1624 		if (i >= fd_cd.cd_ndevs) {
   1625 			i = -1;
   1626 			continue;
   1627 		}
   1628 		if ((sc = device_lookup_private(&fd_cd, i)) == NULL)
   1629 			continue;
   1630 
   1631 		/*
   1632 		 * if unit has requested to be turned off
   1633 		 * and it has no buf's queued do it now
   1634 		 */
   1635 		if (sc->flags & FDF_MOTOROFF) {
   1636 			if (bufq_peek(sc->bufq) == NULL)
   1637 				fdmotoroff(sc);
   1638 			else {
   1639 				/*
   1640 				 * we gained a buf request while
   1641 				 * we waited, forget the motoroff
   1642 				 */
   1643 				sc->flags &= ~FDF_MOTOROFF;
   1644 			}
   1645 			/*
   1646 			 * if we now have DMA unit must have needed
   1647 			 * flushing, quit
   1648 			 */
   1649 			if (fdc_indma)
   1650 				return;
   1651 		}
   1652 		/*
   1653 		 * if we have no start unit and the current unit has
   1654 		 * io waiting choose this unit to start.
   1655 		 */
   1656 		if (ssc == NULL && bufq_peek(sc->bufq) != NULL)
   1657 			ssc = sc;
   1658 	}
   1659 	if (ssc)
   1660 		fdstart(ssc);
   1661 }
   1662 
   1663 /*
   1664  * min byte count to whats left of the track in question
   1665  */
   1666 void
   1667 fdminphys(struct buf *bp)
   1668 {
   1669 	struct fd_softc *sc;
   1670 	int sec, toff, tsz;
   1671 
   1672 	if ((sc = getsoftc(fd_cd, FDUNIT(bp->b_dev))) == NULL)
   1673 		panic("fdminphys: couldn't get softc");
   1674 
   1675 	sec = bp->b_blkno % sc->nsectors;
   1676 
   1677 	toff = sec * FDSECSIZE;
   1678 	tsz = sc->nsectors * FDSECSIZE;
   1679 #ifdef FDDEBUG
   1680 	printf("fdminphys: before %ld", bp->b_bcount);
   1681 #endif
   1682 	bp->b_bcount = min(bp->b_bcount, tsz - toff);
   1683 #ifdef FDDEBUG
   1684 	printf(" after %ld\n", bp->b_bcount);
   1685 #endif
   1686 	minphys(bp);
   1687 }
   1688 
   1689 /*
   1690  * encode the track cache into raw MFM ready for DMA
   1691  * when we go to multiple disk formats, this will call type dependent
   1692  * functions
   1693  */
   1694 void fdcachetoraw(struct fd_softc *sc)
   1695 {
   1696 	if (sc->openpart == FDMSDOSPART)
   1697 		mscachetoraw(sc);
   1698 	else
   1699 		amcachetoraw(sc);
   1700 }
   1701 
   1702 /*
   1703  * decode raw MFM from DMA into units track cache.
   1704  * when we go to multiple disk formats, this will call type dependent
   1705  * functions
   1706  */
   1707 int
   1708 fdrawtocache(struct fd_softc *sc)
   1709 {
   1710 
   1711 	if (sc->openpart == FDMSDOSPART)
   1712 		return(msrawtocache(sc));
   1713 	else
   1714 		return(amrawtocache(sc));
   1715 }
   1716 
   1717 void
   1718 amcachetoraw(struct fd_softc *sc)
   1719 {
   1720 	static u_long mfmnull[4];
   1721 	u_long *rp, *crp, *dp, hcksum, dcksum, info;
   1722 	int sec, i;
   1723 
   1724 	rp = fdc_dmap;
   1725 
   1726 	/*
   1727 	 * not yet one sector (- 1 long) gap.
   1728 	 * for now use previous drivers values
   1729 	 */
   1730 	for (i = 0; i < sc->type->gap; i++)
   1731 		*rp++ = 0xaaaaaaaa;
   1732 	/*
   1733 	 * process sectors
   1734 	 */
   1735 	dp = sc->cachep;
   1736 	info = 0xff000000 | (sc->cachetrk << 16) | sc->nsectors;
   1737 	for (sec = 0; sec < sc->nsectors; sec++, info += (1 << 8) - 1) {
   1738 		hcksum = dcksum = 0;
   1739 		/*
   1740 		 * sector format
   1741 		 *	offset		description
   1742 		 *-----------------------------------
   1743 		 *  0			null
   1744 		 *  1			sync
   1745 		 * oddbits	evenbits
   1746 		 *----------------------
   1747 		 *  2		3	[0xff]b [trk]b [sec]b [togap]b
   1748 		 *  4-7		8-11	null
   1749 		 * 12		13	header cksum [2-11]
   1750 		 * 14		15	data cksum [16-271]
   1751 		 * 16-143	144-271	data
   1752 		 */
   1753 		*rp = 0xaaaaaaaa;
   1754 		if (*(rp - 1) & 0x1)
   1755 			*rp &= 0x7fffffff;	/* clock bit correction */
   1756 		rp++;
   1757 		*rp++ = (FDMFMSYNC << 16) | FDMFMSYNC;
   1758 		rp = mfmblkencode(&info, rp, &hcksum, 1);
   1759 		rp = mfmblkencode(mfmnull, rp, &hcksum, 4);
   1760 		rp = mfmblkencode(&hcksum, rp, NULL, 1);
   1761 
   1762 		crp = rp;
   1763 		rp = mfmblkencode(dp, rp + 2, &dcksum, FDSECLWORDS);
   1764 		dp += FDSECLWORDS;
   1765 		crp = mfmblkencode(&dcksum, crp, NULL, 1);
   1766 		if (*(crp - 1) & 0x1)
   1767 			*crp &= 0x7fffffff;	/* clock bit correction */
   1768 		else if ((*crp & 0x40000000) == 0)
   1769 			*crp |= 0x80000000;
   1770 	}
   1771 	*rp = 0xaaa80000;
   1772 	if (*(rp - 1) & 0x1)
   1773 		*rp &= 0x7fffffff;
   1774 }
   1775 
   1776 u_long *
   1777 fdfindsync(u_long *rp, u_long *ep)
   1778 {
   1779 	u_short *sp;
   1780 
   1781 	sp = (u_short *)rp;
   1782 	while ((u_long *)sp < ep && *sp != FDMFMSYNC)
   1783 		sp++;
   1784 	while ((u_long *)sp < ep && *sp == FDMFMSYNC)
   1785 		sp++;
   1786 	if ((u_long *)sp < ep)
   1787 		return((u_long *)sp);
   1788 	return(NULL);
   1789 }
   1790 
   1791 int
   1792 amrawtocache(struct fd_softc *sc)
   1793 {
   1794 	u_long mfmnull[4];
   1795 	u_long *dp, *rp, *erp, *crp, *srp, hcksum, dcksum, info, cktmp;
   1796 	int cnt, doagain;
   1797 
   1798 	doagain = 1;
   1799 	srp = rp = fdc_dmap;
   1800 	erp = (u_long *)((u_short *)rp + sc->type->nreadw);
   1801 	cnt = 0;
   1802 again:
   1803 	if (doagain == 0 || (rp = srp = fdfindsync(srp, erp)) == NULL) {
   1804 #ifdef DIAGNOSTIC
   1805 		aprint_error_dev(sc->sc_dev, "corrupted track (%d) data.\n",
   1806 		    sc->cachetrk);
   1807 #endif
   1808 		return(-1);
   1809 	}
   1810 
   1811 	/*
   1812 	 * process sectors
   1813 	 */
   1814 	for (; cnt < sc->nsectors; cnt++) {
   1815 		hcksum = dcksum = 0;
   1816 		rp = mfmblkdecode(rp, &info, &hcksum, 1);
   1817 		rp = mfmblkdecode(rp, mfmnull, &hcksum, 4);
   1818 		rp = mfmblkdecode(rp, &cktmp, NULL, 1);
   1819 		if (cktmp != hcksum) {
   1820 #ifdef FDDEBUG
   1821 			printf("  info 0x%lx hchksum 0x%lx trkhcksum 0x%lx\n",
   1822 			    info, hcksum, cktmp);
   1823 #endif
   1824 			goto again;
   1825 		}
   1826 		if (((info >> 16) & 0xff) != sc->cachetrk) {
   1827 #ifdef DEBUG
   1828 			aprint_debug_dev(sc->sc_dev,
   1829 			    "incorrect track found: 0x%lx %d\n",
   1830 			    info, sc->cachetrk);
   1831 #endif
   1832 			goto again;
   1833 		}
   1834 #ifdef FDDEBUG
   1835 		printf("  info 0x%lx\n", info);
   1836 #endif
   1837 
   1838 		rp = mfmblkdecode(rp, &cktmp, NULL, 1);
   1839 		dp = sc->cachep;
   1840 		dp += FDSECLWORDS * ((info >> 8) & 0xff);
   1841 		crp = mfmblkdecode(rp, dp, &dcksum, FDSECLWORDS);
   1842 		if (cktmp != dcksum) {
   1843 #ifdef FDDEBUG
   1844 			printf("  info 0x%lx dchksum 0x%lx trkdcksum 0x%lx\n",
   1845 			    info, dcksum, cktmp);
   1846 #endif
   1847 			goto again;
   1848 		}
   1849 
   1850 		/*
   1851 		 * if we are at gap then we can no longer be sure
   1852 		 * of correct sync marks
   1853 		 */
   1854 		if ((info & 0xff) == 1)
   1855 			doagain = 1;
   1856 		else
   1857 			doagain = 0;
   1858 		srp = rp = fdfindsync(crp, erp);
   1859 	}
   1860 	return(0);
   1861 }
   1862 
   1863 void
   1864 mscachetoraw(struct fd_softc *sc)
   1865 {
   1866 	u_short *rp, *erp, crc;
   1867 	u_char *cp, tb[5];
   1868 	int sec, i;
   1869 
   1870 	rp = (u_short *)fdc_dmap;
   1871 	erp = rp + sc->type->nwritew;
   1872 	cp = sc->cachep;
   1873 
   1874 	/*
   1875 	 * initial track filler  (828 * GAP1)
   1876 	 */
   1877 	for (i = 0; i < sc->type->gap; i++) {
   1878 		*rp++ = FDMFMGAP1;
   1879 		*rp++ = FDMFMGAP1;
   1880 	}
   1881 
   1882 	for (sec = 0; sec < sc->nsectors; sec++) {
   1883 
   1884 		/*
   1885 		 * leading sector gap
   1886 		 * (12 * GAP2) + (3 * SYNC)
   1887 		 */
   1888 		for (i = 0; i < 12; i++)
   1889 			*rp++ = FDMFMGAP2;
   1890 		*rp++ = FDMFMSYNC;
   1891 		*rp++ = FDMFMSYNC;
   1892 		*rp++ = FDMFMSYNC;
   1893 
   1894 		/*
   1895 		 * sector information
   1896 		 * (ID) + track + side + sector + sector size + CRC16
   1897 		 */
   1898 		*rp++ = FDMFMID;
   1899 		tb[0] = sc->cachetrk / FDNHEADS;
   1900 		tb[1] = sc->cachetrk % FDNHEADS;
   1901 		tb[2] = sec + 1;
   1902 		i = sc->bytespersec;
   1903 		tb[3] = i < 256 ? 0 : (i < 512 ? 1 : (i < 1024 ? 2 : 3));
   1904 		rp = msblkencode(rp, tb, 4, &crc);
   1905 		tb[0] = crc >> 8;
   1906 		tb[1] = crc & 0xff;
   1907 		tb[2] = 0x4e; /* GAP1 decoded */
   1908 		rp = msblkencode(rp, tb, 3, 0);
   1909 
   1910 		/*
   1911 		 * sector info/data gap
   1912 		 * (22 * GAP1) + (12 * GAP2) + (3 * SYNC)
   1913 		 */
   1914 		for (i = 0; i < 21; i++)
   1915 			*rp++ = FDMFMGAP1;
   1916 		for (i = 0; i < 12; i++)
   1917 			*rp++ = FDMFMGAP2;
   1918 		*rp++ = FDMFMSYNC;
   1919 		*rp++ = FDMFMSYNC;
   1920 		*rp++ = FDMFMSYNC;
   1921 
   1922 		/*
   1923 		 * sector data
   1924 		 * (DATA) + ...data... + CRC16
   1925 		 */
   1926 		*rp++ = FDMFMDATA;
   1927 		rp = msblkencode(rp, cp, sc->bytespersec, &crc);
   1928 		cp += sc->bytespersec;
   1929 		tb[0] = crc >> 8;
   1930 		tb[1] = crc & 0xff;
   1931 		tb[2] = 0x4e; /* GAP3 decoded */
   1932 		rp = msblkencode(rp, tb, 3, 0);
   1933 
   1934 		/*
   1935 		 * trailing sector gap
   1936 		 * (80 * GAP3)
   1937 		 */
   1938 		for (i = 0; i < 79; i++)
   1939 			*rp++ = FDMFMGAP3;
   1940 	}
   1941 
   1942 	/*
   1943 	 * fill rest of track with GAP3
   1944 	 */
   1945 	while (rp != erp)
   1946 		*rp++ = FDMFMGAP3;
   1947 
   1948 }
   1949 
   1950 int
   1951 msrawtocache(struct fd_softc *sc)
   1952 {
   1953 	u_short *rp, *erp;
   1954 	u_char tb[5], *cp;
   1955 	int ct, sec, retry;
   1956 
   1957 	rp = (u_short *)fdc_dmap;
   1958 	erp = rp + sc->type->nreadw;
   1959 	cp = sc->cachep;
   1960 
   1961 	for (ct = 0; ct < sc->nsectors; ct++) {
   1962 		retry = 1;
   1963 		do {
   1964 			/*
   1965 			 * skip leading gap to sync
   1966 			 */
   1967 			if ((rp = (u_short *)fdfindsync((u_long *)rp, (u_long *)erp)) == NULL) {
   1968 #ifdef DIAGNOSTIC
   1969 				aprint_normal_dev(sc->sc_dev,
   1970 				    "corrupted track (%d) data.\n",
   1971 				    sc->cachetrk);
   1972 #endif
   1973 				return(-1);
   1974 			}
   1975 
   1976 			/*
   1977 			 * Grab sector info
   1978 			 */
   1979 			if (*rp++ != FDMFMID)
   1980 				continue;
   1981 			rp = msblkdecode(rp, tb, 4);
   1982 #ifdef FDDEBUG
   1983 			printf("sector id: sector %d, track %d, side %d,"
   1984 			    "bps %d\n", tb[2], tb[0], tb[1], 128 << tb[3]);
   1985 #endif
   1986 			if ((tb[0] * FDNHEADS + tb[1]) != sc->cachetrk ||
   1987 			    tb[2] > sc->nsectors)
   1988 				continue;
   1989 
   1990 			sec = tb[2];
   1991 			sc->bytespersec = 128 << tb[3];
   1992 			rp += 2; /* skip CRC-16 */
   1993 
   1994 			/*
   1995 			 * skip gap and read in data
   1996 			 */
   1997 			if ((rp = (u_short *)fdfindsync((u_long *)rp, (u_long *)erp)) == NULL)
   1998 				return(-1);
   1999 			if (*rp++ != FDMFMDATA)
   2000 				continue;
   2001 			rp = msblkdecode(rp, cp + ((sec-1) * sc->bytespersec),
   2002 			    sc->bytespersec);
   2003 			rp += 2; /* skip CRC-16 */
   2004 
   2005 			retry = 0;
   2006 		} while (retry);
   2007 	}
   2008 	return(0);
   2009 }
   2010 
   2011 /*
   2012  * encode len longwords of `dp' data in amiga mfm block format (`rp')
   2013  * this format specified that the odd bits are at current pos and even
   2014  * bits at len + current pos
   2015  */
   2016 u_long *
   2017 mfmblkencode(u_long *dp, u_long *rp, u_long *cp, int len)
   2018 {
   2019 	u_long *sdp, *edp, d, dtmp, correct;
   2020 
   2021 	sdp = dp;
   2022 	edp = dp + len;
   2023 
   2024 	if (*(rp - 1) & 0x1)
   2025 		correct = 1;
   2026 	else
   2027 		correct = 0;
   2028 	/*
   2029 	 * do odd bits
   2030 	 */
   2031 	while (dp < edp) {
   2032 		d = (*dp >> 1) & 0x55555555;	/* remove clock bits */
   2033 		dtmp = d ^ 0x55555555;
   2034 		d |= ((dtmp >> 1) | 0x80000000) & (dtmp << 1);
   2035 		/*
   2036 		 * correct upper clock bit if needed
   2037 		 */
   2038 		if (correct)
   2039 			d &= 0x7fffffff;
   2040 		if (d & 0x1)
   2041 			correct = 1;
   2042 		else
   2043 			correct = 0;
   2044 		/*
   2045 		 * do checksums and store in raw buffer
   2046 		 */
   2047 		if (cp)
   2048 			*cp ^= d;
   2049 		*rp++ = d;
   2050 		dp++;
   2051 	}
   2052 	/*
   2053 	 * do even bits
   2054 	 */
   2055 	dp = sdp;
   2056 	while (dp < edp) {
   2057 		d = *dp & 0x55555555;	/* remove clock bits */
   2058 		dtmp = d ^ 0x55555555;
   2059 		d |= ((dtmp >> 1) | 0x80000000) & (dtmp << 1);
   2060 		/*
   2061 		 * correct upper clock bit if needed
   2062 		 */
   2063 		if (correct)
   2064 			d &= 0x7fffffff;
   2065 		if (d & 0x1)
   2066 			correct = 1;
   2067 		else
   2068 			correct = 0;
   2069 		/*
   2070 		 * do checksums and store in raw buffer
   2071 		 */
   2072 		if (cp)
   2073 			*cp ^= d;
   2074 		*rp++ = d;
   2075 		dp++;
   2076 	}
   2077 	if (cp)
   2078 		*cp &= 0x55555555;
   2079 	return(rp);
   2080 }
   2081 
   2082 /*
   2083  * decode len longwords of `dp' data in amiga mfm block format (`rp')
   2084  * this format specified that the odd bits are at current pos and even
   2085  * bits at len + current pos
   2086  */
   2087 u_long *
   2088 mfmblkdecode(u_long *rp, u_long *dp, u_long *cp, int len)
   2089 {
   2090 	u_long o, e;
   2091 	int cnt;
   2092 
   2093 	cnt = len;
   2094 	while (cnt--) {
   2095 		o = *rp;
   2096 		e = *(rp + len);
   2097 		if (cp) {
   2098 			*cp ^= o;
   2099 			*cp ^= e;
   2100 		}
   2101 		o &= 0x55555555;
   2102 		e &= 0x55555555;
   2103 		*dp++ = (o << 1) | e;
   2104 		rp++;
   2105 	}
   2106 	if (cp)
   2107 		*cp &= 0x55555555;
   2108 	return(rp + len);
   2109 }
   2110 
   2111 /*
   2112  * decode len words in standard MFM format to len bytes
   2113  * of data.
   2114  */
   2115 u_short *
   2116 msblkdecode(u_short *rp, u_char *cp, int len)
   2117 {
   2118 	while (len--) {
   2119 		*cp++ = msdecode[*rp & 0x7f] |
   2120 		    (msdecode[(*rp >> 8) & 0x7f] << 4);
   2121 		rp++;
   2122 	}
   2123 
   2124 	return(rp);
   2125 }
   2126 
   2127 /*
   2128  * encode len bytes of data into len words in standard MFM format.
   2129  * If a pointer is supplied for crc, calculate the CRC-16 of the data
   2130  * as well.
   2131  */
   2132 u_short *
   2133 msblkencode(u_short *rp, u_char *cp, int len, u_short *crc)
   2134 {
   2135 	u_short td;
   2136 	u_short mycrc;
   2137 
   2138 	/* preload crc for header (4 bytes)
   2139 	 * or data (anything else)
   2140 	 */
   2141 	mycrc = (len == 4) ? 0xb230 : 0xe295;
   2142 
   2143 	while (len--) {
   2144 		td = (msencode[*cp >> 4] << 8) | msencode[*cp & 0x0f];
   2145 
   2146 		/* Check for zeros in top bit of encode and bottom
   2147 		 * bit of previous encode.  if so, slap a one in betweem
   2148 		 * them.
   2149 		 */
   2150 		if ((td & 0x140) == 0)
   2151 			td |= 0x80;
   2152 		if ((td & 0x4000) == 0 && (rp[-1] & 1) == 0)
   2153 			td |= 0x8000;
   2154 
   2155 		*rp++ = td;
   2156 
   2157 		/*
   2158 		 * calc crc if requested
   2159 		 */
   2160 		if (crc)
   2161 			mycrc = (mycrc << 8) ^ mscrctab[*cp ^ (mycrc >> 8)];
   2162 
   2163 		cp++;
   2164 	}
   2165 
   2166 	if (crc)
   2167 		*crc = mycrc;
   2168 
   2169 	return(rp);
   2170 }
   2171