fdc.c revision 140469
1/*-
2 * Copyright (c) 2004 Poul-Henning Kamp
3 * Copyright (c) 1990 The Regents of the University of California.
4 * All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * Don Ahn.
8 *
9 * Libretto PCMCIA floppy support by David Horwitt (dhorwitt@ucsd.edu)
10 * aided by the Linux floppy driver modifications from David Bateman
11 * (dbateman@eng.uts.edu.au).
12 *
13 * Copyright (c) 1993, 1994 by
14 *  jc@irbs.UUCP (John Capo)
15 *  vak@zebub.msk.su (Serge Vakulenko)
16 *  ache@astral.msk.su (Andrew A. Chernov)
17 *
18 * Copyright (c) 1993, 1994, 1995 by
19 *  joerg_wunsch@uriah.sax.de (Joerg Wunsch)
20 *  dufault@hda.com (Peter Dufault)
21 *
22 * Copyright (c) 2001 Joerg Wunsch,
23 *  joerg_wunsch@uriah.heep.sax.de (Joerg Wunsch)
24 *
25 * Redistribution and use in source and binary forms, with or without
26 * modification, are permitted provided that the following conditions
27 * are met:
28 * 1. Redistributions of source code must retain the above copyright
29 *    notice, this list of conditions and the following disclaimer.
30 * 2. Redistributions in binary form must reproduce the above copyright
31 *    notice, this list of conditions and the following disclaimer in the
32 *    documentation and/or other materials provided with the distribution.
33 * 4. Neither the name of the University nor the names of its contributors
34 *    may be used to endorse or promote products derived from this software
35 *    without specific prior written permission.
36 *
37 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
38 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
39 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
40 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
41 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
42 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
43 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
45 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
46 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47 * SUCH DAMAGE.
48 *
49 *	from:	@(#)fd.c	7.4 (Berkeley) 5/25/91
50 *
51 */
52
53#include <sys/cdefs.h>
54__FBSDID("$FreeBSD: head/sys/dev/fdc/fdc.c 140469 2005-01-19 07:46:38Z imp $");
55
56#include "opt_fdc.h"
57
58#include <sys/param.h>
59#include <sys/bio.h>
60#include <sys/bus.h>
61#include <sys/devicestat.h>
62#include <sys/disk.h>
63#include <sys/fcntl.h>
64#include <sys/fdcio.h>
65#include <sys/filio.h>
66#include <sys/kernel.h>
67#include <sys/kthread.h>
68#include <sys/lock.h>
69#include <sys/malloc.h>
70#include <sys/module.h>
71#include <sys/mutex.h>
72#include <sys/proc.h>
73#include <sys/rman.h>
74#include <sys/sysctl.h>
75#include <sys/systm.h>
76
77#include <geom/geom.h>
78
79#include <machine/bus.h>
80#include <machine/clock.h>
81#include <machine/stdarg.h>
82
83#include <isa/isavar.h>
84#include <isa/isareg.h>
85#include <dev/fdc/fdcvar.h>
86#include <isa/rtc.h>
87
88#include <dev/ic/nec765.h>
89
90/*
91 * Runtime configuration hints/flags
92 */
93
94/* configuration flags for fd */
95#define FD_TYPEMASK	0x0f	/* drive type, matches enum
96				 * fd_drivetype; on i386 machines, if
97				 * given as 0, use RTC type for fd0
98				 * and fd1 */
99#define FD_NO_PROBE	0x20	/* don't probe drive (seek test), just
100				 * assume it is there */
101
102/*
103 * Things that could conceiveably considered parameters or tweakables
104 */
105
106/*
107 * Maximal number of bytes in a cylinder.
108 * This is used for ISADMA bouncebuffer allocation and sets the max
109 * xfersize we support.
110 *
111 * 2.88M format has 2 x 36 x 512, allow for hacked up density.
112 */
113#define MAX_BYTES_PER_CYL	(2 * 40 * 512)
114
115/*
116 * Timeout value for the PIO loops to wait until the FDC main status
117 * register matches our expectations (request for master, direction
118 * bit).  This is supposed to be a number of microseconds, although
119 * timing might actually not be very accurate.
120 *
121 * Timeouts of 100 msec are believed to be required for some broken
122 * (old) hardware.
123 */
124#define	FDSTS_TIMEOUT	100000
125
126/*
127 * After this many errors, stop whining.  Close will reset this count.
128 */
129#define FDC_ERRMAX	100
130
131/*
132 * AutoDensity search lists for each drive type.
133 */
134
135static struct fd_type fd_searchlist_360k[] = {
136	{ FDF_5_360 },
137	{ 0 }
138};
139
140static struct fd_type fd_searchlist_12m[] = {
141	{ FDF_5_1200 | FL_AUTO },
142	{ FDF_5_360 | FL_2STEP | FL_AUTO},
143	{ 0 }
144};
145
146static struct fd_type fd_searchlist_720k[] = {
147	{ FDF_3_720 },
148	{ 0 }
149};
150
151static struct fd_type fd_searchlist_144m[] = {
152	{ FDF_3_1440 | FL_AUTO},
153	{ FDF_3_720 | FL_AUTO},
154	{ 0 }
155};
156
157static struct fd_type fd_searchlist_288m[] = {
158	{ FDF_3_1440 | FL_AUTO },
159#if 0
160	{ FDF_3_2880 | FL_AUTO }, /* XXX: probably doesn't work */
161#endif
162	{ FDF_3_720 | FL_AUTO},
163	{ 0 }
164};
165
166/*
167 * Order must match enum fd_drivetype in <sys/fdcio.h>.
168 */
169static struct fd_type *fd_native_types[] = {
170	NULL,				/* FDT_NONE */
171	fd_searchlist_360k, 		/* FDT_360K */
172	fd_searchlist_12m, 		/* FDT_12M */
173	fd_searchlist_720k, 		/* FDT_720K */
174	fd_searchlist_144m, 		/* FDT_144M */
175	fd_searchlist_288m,		/* FDT_288M_1 (mapped to FDT_288M) */
176	fd_searchlist_288m, 		/* FDT_288M */
177};
178
179/*
180 * Internals start here
181 */
182
183/* registers */
184#define	FDOUT	2	/* Digital Output Register (W) */
185#define	FDO_FDSEL	0x03	/*  floppy device select */
186#define	FDO_FRST	0x04	/*  floppy controller reset */
187#define	FDO_FDMAEN	0x08	/*  enable floppy DMA and Interrupt */
188#define	FDO_MOEN0	0x10	/*  motor enable drive 0 */
189#define	FDO_MOEN1	0x20	/*  motor enable drive 1 */
190#define	FDO_MOEN2	0x40	/*  motor enable drive 2 */
191#define	FDO_MOEN3	0x80	/*  motor enable drive 3 */
192
193#define	FDSTS	4	/* NEC 765 Main Status Register (R) */
194#define	FDDATA	5	/* NEC 765 Data Register (R/W) */
195#define	FDCTL	7	/* Control Register (W) */
196
197/*
198 * The YE-DATA PC Card floppies use PIO to read in the data rather
199 * than DMA due to the wild variability of DMA for the PC Card
200 * devices.  DMA was deleted from the PC Card specification in version
201 * 7.2 of the standard, but that post-dates the YE-DATA devices by many
202 * years.
203 *
204 * In addition, if we cannot setup the DMA resources for the ISA
205 * attachment, we'll use this same offset for data transfer.  However,
206 * that almost certainly won't work.
207 *
208 * For this mode, offset 0 and 1 must be used to setup the transfer
209 * for this floppy.  This is OK for PC Card YE Data devices, but for
210 * ISA this is likely wrong.  These registers are only available on
211 * those systems that map them to the floppy drive.  Newer systems do
212 * not do this, and we should likely prohibit access to them (or
213 * disallow NODMA to be set).
214 */
215#define FDBCDR		0	/* And 1 */
216#define FD_YE_DATAPORT	6	/* Drive Data port */
217
218#define	FDI_DCHG	0x80	/* diskette has been changed */
219				/* requires drive and motor being selected */
220				/* is cleared by any step pulse to drive */
221
222/*
223 * We have three private BIO commands.
224 */
225#define BIO_PROBE	BIO_CMD0
226#define BIO_RDID	BIO_CMD1
227#define BIO_FMT		BIO_CMD2
228
229/*
230 * Per drive structure (softc).
231 */
232struct fd_data {
233	u_char 	*fd_ioptr;	/* IO pointer */
234	u_int	fd_iosize;	/* Size of IO chunks */
235	u_int	fd_iocount;	/* Outstanding requests */
236	struct	fdc_data *fdc;	/* pointer to controller structure */
237	int	fdsu;		/* this units number on this controller */
238	enum	fd_drivetype type; /* drive type */
239	struct	fd_type *ft;	/* pointer to current type descriptor */
240	struct	fd_type fts;	/* type descriptors */
241	int	sectorsize;
242	int	flags;
243#define	FD_WP		(1<<0)	/* Write protected	*/
244#define	FD_MOTOR	(1<<1)	/* motor should be on	*/
245#define	FD_MOTORWAIT	(1<<2)	/* motor should be on	*/
246#define	FD_EMPTY	(1<<3)	/* no media		*/
247#define	FD_NEWDISK	(1<<4)	/* media changed	*/
248#define	FD_ISADMA	(1<<5)	/* isa dma started 	*/
249	int	track;		/* where we think the head is */
250#define FD_NO_TRACK	 -2
251	int	options;	/* FDOPT_* */
252	struct	callout toffhandle;
253	struct	callout tohandle;
254	struct g_geom *fd_geom;
255	struct g_provider *fd_provider;
256	device_t dev;
257	struct bio_queue_head fd_bq;
258};
259
260#define FD_NOT_VALID -2
261
262static driver_intr_t fdc_intr;
263static void fdc_reset(struct fdc_data *);
264
265SYSCTL_NODE(_debug, OID_AUTO, fdc, CTLFLAG_RW, 0, "fdc driver");
266
267static int fifo_threshold = 8;
268SYSCTL_INT(_debug_fdc, OID_AUTO, fifo, CTLFLAG_RW, &fifo_threshold, 0,
269	"FIFO threshold setting");
270
271static int debugflags = 0;
272SYSCTL_INT(_debug_fdc, OID_AUTO, debugflags, CTLFLAG_RW, &debugflags, 0,
273	"Debug flags");
274
275static int retries = 10;
276SYSCTL_INT(_debug_fdc, OID_AUTO, retries, CTLFLAG_RW, &retries, 0,
277	"Number of retries to attempt");
278
279static int spec1 = 0xaf;
280SYSCTL_INT(_debug_fdc, OID_AUTO, spec1, CTLFLAG_RW, &spec1, 0,
281	"Specification byte one (step-rate + head unload)");
282
283static int spec2 = 0x10;
284SYSCTL_INT(_debug_fdc, OID_AUTO, spec2, CTLFLAG_RW, &spec2, 0,
285	"Specification byte two (head load time + no-dma)");
286
287static int settle;
288SYSCTL_INT(_debug_fdc, OID_AUTO, settle, CTLFLAG_RW, &settle, 0,
289	"Head settling time in sec/hz");
290
291static void
292fdprinttype(struct fd_type *ft)
293{
294
295	printf("(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,0x%x)",
296	    ft->sectrac, ft->secsize, ft->datalen, ft->gap, ft->tracks,
297	    ft->size, ft->trans, ft->heads, ft->f_gap, ft->f_inter,
298	    ft->offset_side2, ft->flags);
299}
300
301static void
302fdsettype(struct fd_data *fd, struct fd_type *ft)
303{
304	fd->ft = ft;
305	ft->size = ft->sectrac * ft->heads * ft->tracks;
306	fd->sectorsize = 128 << fd->ft->secsize;
307}
308
309/*
310 * Bus space handling (access to low-level IO).
311 */
312__inline static void
313fdregwr(struct fdc_data *fdc, int reg, uint8_t v)
314{
315
316	bus_space_write_1(fdc->iot, fdc->ioh[reg], fdc->ioff[reg], v);
317}
318
319__inline static uint8_t
320fdregrd(struct fdc_data *fdc, int reg)
321{
322
323	return bus_space_read_1(fdc->iot, fdc->ioh[reg], fdc->ioff[reg]);
324}
325
326static void
327fdctl_wr(struct fdc_data *fdc, u_int8_t v)
328{
329
330	fdregwr(fdc, FDCTL, v);
331}
332
333static void
334fdout_wr(struct fdc_data *fdc, u_int8_t v)
335{
336
337	fdregwr(fdc, FDOUT, v);
338}
339
340static u_int8_t
341fdsts_rd(struct fdc_data *fdc)
342{
343
344	return fdregrd(fdc, FDSTS);
345}
346
347static void
348fddata_wr(struct fdc_data *fdc, u_int8_t v)
349{
350
351	fdregwr(fdc, FDDATA, v);
352}
353
354static u_int8_t
355fddata_rd(struct fdc_data *fdc)
356{
357
358	return fdregrd(fdc, FDDATA);
359}
360
361static u_int8_t
362fdin_rd(struct fdc_data *fdc)
363{
364
365	return fdregrd(fdc, FDCTL);
366}
367
368/*
369 * Magic pseudo-DMA initialization for YE FDC. Sets count and
370 * direction.
371 */
372static void
373fdbcdr_wr(struct fdc_data *fdc, int iswrite, uint16_t count)
374{
375	fdregwr(fdc, FDBCDR, (count - 1) & 0xff);
376	fdregwr(fdc, FDBCDR + 1,
377	    (iswrite ? 0x80 : 0) | (((count - 1) >> 8) & 0x7f));
378}
379
380static int
381fdc_err(struct fdc_data *fdc, const char *s)
382{
383	fdc->fdc_errs++;
384	if (s) {
385		if (fdc->fdc_errs < FDC_ERRMAX)
386			device_printf(fdc->fdc_dev, "%s", s);
387		else if (fdc->fdc_errs == FDC_ERRMAX)
388			device_printf(fdc->fdc_dev, "too many errors, not "
389						    "logging any more\n");
390	}
391
392	return (1);
393}
394
395/*
396 * FDC IO functions, take care of the main status register, timeout
397 * in case the desired status bits are never set.
398 *
399 * These PIO loops initially start out with short delays between
400 * each iteration in the expectation that the required condition
401 * is usually met quickly, so it can be handled immediately.
402 */
403static int
404fdc_in(struct fdc_data *fdc, int *ptr)
405{
406	int i, j, step;
407
408	step = 1;
409	for (j = 0; j < FDSTS_TIMEOUT; j += step) {
410	        i = fdsts_rd(fdc) & (NE7_DIO | NE7_RQM);
411	        if (i == (NE7_DIO|NE7_RQM)) {
412			i = fddata_rd(fdc);
413			if (ptr)
414				*ptr = i;
415			return (0);
416		}
417		if (i == NE7_RQM)
418			return (fdc_err(fdc, "ready for output in input\n"));
419		step += step;
420		DELAY(step);
421	}
422	return (fdc_err(fdc, bootverbose? "input ready timeout\n": 0));
423}
424
425static int
426fdc_out(struct fdc_data *fdc, int x)
427{
428	int i, j, step;
429
430	step = 1;
431	for (j = 0; j < FDSTS_TIMEOUT; j += step) {
432	        i = fdsts_rd(fdc) & (NE7_DIO | NE7_RQM);
433	        if (i == NE7_RQM) {
434			fddata_wr(fdc, x);
435			return (0);
436		}
437		if (i == (NE7_DIO|NE7_RQM))
438			return (fdc_err(fdc, "ready for input in output\n"));
439		step += step;
440		DELAY(step);
441	}
442	return (fdc_err(fdc, bootverbose? "output ready timeout\n": 0));
443}
444
445/*
446 * fdc_cmd: Send a command to the chip.
447 * Takes a varargs with this structure:
448 *	# of output bytes
449 *	output bytes as int [...]
450 *	# of input bytes
451 *	input bytes as int* [...]
452 */
453static int
454fdc_cmd(struct fdc_data *fdc, int n_out, ...)
455{
456	u_char cmd = 0;
457	int n_in;
458	int n, i;
459	va_list ap;
460
461	va_start(ap, n_out);
462	for (n = 0; n < n_out; n++) {
463		i = va_arg(ap, int);
464		if (n == 0)
465			cmd = i;
466		if (fdc_out(fdc, i) < 0) {
467			char msg[50];
468			snprintf(msg, sizeof(msg),
469				"cmd %x failed at out byte %d of %d\n",
470				cmd, n + 1, n_out);
471			fdc->flags |= FDC_NEEDS_RESET;
472			return fdc_err(fdc, msg);
473		}
474	}
475	n_in = va_arg(ap, int);
476	for (n = 0; n < n_in; n++) {
477		int *ptr = va_arg(ap, int *);
478		if (fdc_in(fdc, ptr) < 0) {
479			char msg[50];
480			snprintf(msg, sizeof(msg),
481				"cmd %02x failed at in byte %d of %d\n",
482				cmd, n + 1, n_in);
483			fdc->flags |= FDC_NEEDS_RESET;
484			return fdc_err(fdc, msg);
485		}
486	}
487	return (0);
488}
489
490static void
491fdc_reset(struct fdc_data *fdc)
492{
493	int i, r[10];
494
495	/* Try a reset, keep motor on */
496	fdout_wr(fdc, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
497	DELAY(100);
498	/* enable FDC, but defer interrupts a moment */
499	fdout_wr(fdc, fdc->fdout & ~FDO_FDMAEN);
500	DELAY(100);
501	fdout_wr(fdc, fdc->fdout);
502
503	/* XXX after a reset, silently believe the FDC will accept commands */
504	if (fdc_cmd(fdc, 3, NE7CMD_SPECIFY, spec1, spec2, 0))
505		device_printf(fdc->fdc_dev, " SPECIFY failed in reset\n");
506
507	if (fdc->fdct == FDC_ENHANCED) {
508		if (fdc_cmd(fdc, 4,
509		    I8207X_CONFIGURE,
510		    0,
511		    0x40 |			/* Enable Implied Seek */
512		    0x10 |			/* Polling disabled */
513		    (fifo_threshold - 1),	/* Fifo threshold */
514		    0x00,			/* Precomp track */
515		    0))
516			device_printf(fdc->fdc_dev,
517			    " CONFIGURE failed in reset\n");
518		if (debugflags & 1) {
519			if (fdc_cmd(fdc, 1,
520			    0x0e,			/* DUMPREG */
521			    10, &r[0], &r[1], &r[2], &r[3], &r[4],
522			    &r[5], &r[6], &r[7], &r[8], &r[9]))
523				device_printf(fdc->fdc_dev,
524				    " DUMPREG failed in reset\n");
525			for (i = 0; i < 10; i++)
526				printf(" %02x", r[i]);
527			printf("\n");
528		}
529	}
530}
531
532static int
533fdc_sense_drive(struct fdc_data *fdc, int *st3p)
534{
535	int st3;
536
537	if (fdc_cmd(fdc, 2, NE7CMD_SENSED, fdc->fd->fdsu, 1, &st3))
538		return (fdc_err(fdc, "Sense Drive Status failed\n"));
539	if (st3p)
540		*st3p = st3;
541	return (0);
542}
543
544static int
545fdc_sense_int(struct fdc_data *fdc, int *st0p, int *cylp)
546{
547	int cyl, st0, ret;
548
549	ret = fdc_cmd(fdc, 1, NE7CMD_SENSEI, 1, &st0);
550	if (ret) {
551		(void)fdc_err(fdc, "sense intr err reading stat reg 0\n");
552		return (ret);
553	}
554
555	if (st0p)
556		*st0p = st0;
557
558	if ((st0 & NE7_ST0_IC) == NE7_ST0_IC_IV) {
559		/*
560		 * There doesn't seem to have been an interrupt.
561		 */
562		return (FD_NOT_VALID);
563	}
564
565	if (fdc_in(fdc, &cyl) < 0)
566		return fdc_err(fdc, "can't get cyl num\n");
567
568	if (cylp)
569		*cylp = cyl;
570
571	return (0);
572}
573
574static int
575fdc_read_status(struct fdc_data *fdc)
576{
577	int i, ret, status;
578
579	for (i = ret = 0; i < 7; i++) {
580		ret = fdc_in(fdc, &status);
581		fdc->status[i] = status;
582		if (ret != 0)
583			break;
584	}
585
586	if (ret == 0)
587		fdc->flags |= FDC_STAT_VALID;
588	else
589		fdc->flags &= ~FDC_STAT_VALID;
590
591	return ret;
592}
593
594/*
595 * Select this drive
596 */
597static void
598fd_select(struct fd_data *fd)
599{
600	struct fdc_data *fdc;
601
602	/* XXX: lock controller */
603	fdc = fd->fdc;
604	fdc->fdout &= ~FDO_FDSEL;
605	fdc->fdout |= FDO_FDMAEN | FDO_FRST | fd->fdsu;
606	fdout_wr(fdc, fdc->fdout);
607}
608
609static void
610fd_turnon(void *arg)
611{
612	struct fd_data *fd;
613	struct bio *bp;
614	int once;
615
616	fd = arg;
617	mtx_lock(&fd->fdc->fdc_mtx);
618	fd->flags &= ~FD_MOTORWAIT;
619	fd->flags |= FD_MOTOR;
620	once = 0;
621	for (;;) {
622		bp = bioq_takefirst(&fd->fd_bq);
623		if (bp == NULL)
624			break;
625		bioq_disksort(&fd->fdc->head, bp);
626		once = 1;
627	}
628	mtx_unlock(&fd->fdc->fdc_mtx);
629	if (once)
630		wakeup(&fd->fdc->head);
631}
632
633static void
634fd_motor(struct fd_data *fd, int turnon)
635{
636	struct fdc_data *fdc;
637
638	fdc = fd->fdc;
639/*
640	mtx_assert(&fdc->fdc_mtx, MA_OWNED);
641*/
642	if (turnon) {
643		fd->flags |= FD_MOTORWAIT;
644		fdc->fdout |= (FDO_MOEN0 << fd->fdsu);
645		callout_reset(&fd->toffhandle, hz, fd_turnon, fd);
646	} else {
647		callout_drain(&fd->toffhandle);
648		fd->flags &= ~(FD_MOTOR|FD_MOTORWAIT);
649		fdc->fdout &= ~(FDO_MOEN0 << fd->fdsu);
650	}
651	fdout_wr(fdc, fdc->fdout);
652}
653
654static void
655fd_turnoff(void *xfd)
656{
657	struct fd_data *fd = xfd;
658
659	mtx_lock(&fd->fdc->fdc_mtx);
660	fd_motor(fd, 0);
661	mtx_unlock(&fd->fdc->fdc_mtx);
662}
663
664/*
665 * fdc_intr - wake up the worker thread.
666 */
667
668static void
669fdc_intr(void *arg)
670{
671
672	wakeup(arg);
673}
674
675/*
676 * fdc_pio(): perform programmed IO read/write for YE PCMCIA floppy.
677 */
678static void
679fdc_pio(struct fdc_data *fdc)
680{
681	u_char *cptr;
682	struct bio *bp;
683	u_int count;
684
685	bp = fdc->bp;
686	cptr = fdc->fd->fd_ioptr;
687	count = fdc->fd->fd_iosize;
688
689	if (bp->bio_cmd == BIO_READ) {
690		fdbcdr_wr(fdc, 0, count);
691		bus_space_read_multi_1(fdc->iot, fdc->ioh[FD_YE_DATAPORT],
692		    fdc->ioff[FD_YE_DATAPORT], cptr, count);
693	} else {
694		bus_space_write_multi_1(fdc->iot, fdc->ioh[FD_YE_DATAPORT],
695		    fdc->ioff[FD_YE_DATAPORT], cptr, count);
696		fdbcdr_wr(fdc, 0, count);	/* needed? */
697	}
698}
699
700static int
701fdc_biodone(struct fdc_data *fdc, int error)
702{
703	struct fd_data *fd;
704	struct bio *bp;
705
706	fd = fdc->fd;
707	bp = fdc->bp;
708
709	mtx_lock(&fdc->fdc_mtx);
710	if (--fd->fd_iocount == 0)
711		callout_reset(&fd->toffhandle, 4 * hz, fd_turnoff, fd);
712	fdc->bp = NULL;
713	fdc->fd = NULL;
714	mtx_unlock(&fdc->fdc_mtx);
715	if (bp->bio_to != NULL) {
716		if ((debugflags & 2) && fd->fdc->retry > 0)
717			printf("retries: %d\n", fd->fdc->retry);
718		g_io_deliver(bp, error);
719		return (0);
720	}
721	bp->bio_error = error;
722	bp->bio_flags |= BIO_DONE;
723	wakeup(bp);
724	return (0);
725}
726
727static int retry_line;
728
729static int
730fdc_worker(struct fdc_data *fdc)
731{
732	struct fd_data *fd;
733	struct bio *bp;
734	int i, nsect;
735	int st0, st3, cyl, mfm, steptrac, cylinder, descyl, sec;
736	int head;
737	static int need_recal;
738	struct fdc_readid *idp;
739	struct fd_formb *finfo;
740
741	/* Have we exhausted our retries ? */
742	bp = fdc->bp;
743	fd = fdc->fd;
744	if (bp != NULL &&
745		(fdc->retry >= retries || (fd->flags & FDOPT_NORETRY))) {
746		if ((debugflags & 4))
747			printf("Too many retries (EIO)\n");
748		return (fdc_biodone(fdc, EIO));
749	}
750
751	/* Disable ISADMA if we bailed while it was active */
752	if (fd != NULL && (fd->flags & FD_ISADMA)) {
753		mtx_lock(&Giant);
754		isa_dmadone(
755		    bp->bio_cmd & BIO_READ ? ISADMA_READ : ISADMA_WRITE,
756		    fd->fd_ioptr, fd->fd_iosize, fdc->dmachan);
757		mtx_unlock(&Giant);
758		mtx_lock(&fdc->fdc_mtx);
759		fd->flags &= ~FD_ISADMA;
760		mtx_unlock(&fdc->fdc_mtx);
761	}
762
763	/* Unwedge the controller ? */
764	if (fdc->flags & FDC_NEEDS_RESET) {
765		fdc->flags &= ~FDC_NEEDS_RESET;
766		fdc_reset(fdc);
767		msleep(fdc, NULL, PRIBIO, "fdcrst", hz);
768		/* Discard results */
769		for (i = 0; i < 4; i++)
770			fdc_sense_int(fdc, &st0, &cyl);
771		/* All drives must recal */
772		need_recal = 0xf;
773	}
774
775	/* Pick up a request, if need be wait for it */
776	if (fdc->bp == NULL) {
777		mtx_lock(&fdc->fdc_mtx);
778		do {
779			fdc->bp = bioq_takefirst(&fdc->head);
780			if (fdc->bp == NULL)
781				msleep(&fdc->head, &fdc->fdc_mtx,
782				    PRIBIO, "-", hz);
783		} while (fdc->bp == NULL &&
784		    (fdc->flags & FDC_KTHREAD_EXIT) == 0);
785		mtx_unlock(&fdc->fdc_mtx);
786
787		if (fdc->bp == NULL)
788			/*
789			 * Nothing to do, worker thread has been
790			 * requested to stop.
791			 */
792			return (0);
793
794		bp = fdc->bp;
795		fd = fdc->fd = bp->bio_driver1;
796		fdc->retry = 0;
797		fd->fd_ioptr = bp->bio_data;
798		if (bp->bio_cmd & BIO_FMT) {
799			i = offsetof(struct fd_formb, fd_formb_cylno(0));
800			fd->fd_ioptr += i;
801			fd->fd_iosize = bp->bio_length - i;
802		}
803	}
804
805	/* Select drive, setup params */
806	fd_select(fd);
807	fdctl_wr(fdc, fd->ft->trans);
808
809	if (bp->bio_cmd & BIO_PROBE) {
810
811		if (!(fdin_rd(fdc) & FDI_DCHG) && !(fd->flags & FD_EMPTY))
812			return (fdc_biodone(fdc, 0));
813
814		/*
815		 * Try to find out if we have a disk in the drive
816		 *
817		 * First recal, then seek to cyl#1, this clears the
818		 * old condition on the disk change line so we can
819		 * examine it for current status
820		 */
821		if (debugflags & 0x40)
822			printf("New disk in probe\n");
823		mtx_lock(&fdc->fdc_mtx);
824		fd->flags |= FD_NEWDISK;
825		mtx_unlock(&fdc->fdc_mtx);
826		retry_line = __LINE__;
827		if (fdc_cmd(fdc, 2, NE7CMD_RECAL, fd->fdsu, 0))
828			return (1);
829		msleep(fdc, NULL, PRIBIO, "fdrecal", hz);
830		retry_line = __LINE__;
831		if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
832			return (1); /* XXX */
833		retry_line = __LINE__;
834		if ((st0 & 0xc0) || cyl != 0)
835			return (1);
836
837		/* Seek to track 1 */
838		retry_line = __LINE__;
839		if (fdc_cmd(fdc, 3, NE7CMD_SEEK, fd->fdsu, 1, 0))
840			return (1);
841		msleep(fdc, NULL, PRIBIO, "fdseek", hz);
842		retry_line = __LINE__;
843		if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
844			return (1); /* XXX */
845		need_recal |= (1 << fd->fdsu);
846		if (fdin_rd(fdc) & FDI_DCHG) {
847			if (debugflags & 0x40)
848				printf("Empty in probe\n");
849			mtx_lock(&fdc->fdc_mtx);
850			fd->flags |= FD_EMPTY;
851			mtx_unlock(&fdc->fdc_mtx);
852		} else {
853			if (debugflags & 0x40)
854				printf("Got disk in probe\n");
855			mtx_lock(&fdc->fdc_mtx);
856			fd->flags &= ~FD_EMPTY;
857			mtx_unlock(&fdc->fdc_mtx);
858			retry_line = __LINE__;
859			if(fdc_sense_drive(fdc, &st3) != 0)
860				return (1);
861			mtx_lock(&fdc->fdc_mtx);
862			if(st3 & NE7_ST3_WP)
863				fd->flags |= FD_WP;
864			else
865				fd->flags &= ~FD_WP;
866			mtx_unlock(&fdc->fdc_mtx);
867		}
868		return (fdc_biodone(fdc, 0));
869	}
870
871	/*
872	 * If we are dead just flush the requests
873	 */
874	if (fd->flags & FD_EMPTY)
875		return (fdc_biodone(fdc, ENXIO));
876
877	/* Check if we lost our media */
878	if (fdin_rd(fdc) & FDI_DCHG) {
879		if (debugflags & 0x40)
880			printf("Lost disk\n");
881		mtx_lock(&fdc->fdc_mtx);
882		fd->flags |= FD_EMPTY;
883		fd->flags |= FD_NEWDISK;
884		mtx_unlock(&fdc->fdc_mtx);
885		g_topology_lock();
886		g_orphan_provider(fd->fd_provider, EXDEV);
887		fd->fd_provider->flags |= G_PF_WITHER;
888		fd->fd_provider =
889		    g_new_providerf(fd->fd_geom, fd->fd_geom->name);
890		g_error_provider(fd->fd_provider, 0);
891		g_topology_unlock();
892		return (fdc_biodone(fdc, ENXIO));
893	}
894
895	/* Check if the floppy is write-protected */
896	if(bp->bio_cmd & (BIO_FMT | BIO_WRITE)) {
897		retry_line = __LINE__;
898		if(fdc_sense_drive(fdc, &st3) != 0)
899			return (1);
900		if(st3 & NE7_ST3_WP)
901			return (fdc_biodone(fdc, EROFS));
902	}
903
904	mfm = (fd->ft->flags & FL_MFM)? NE7CMD_MFM: 0;
905	steptrac = (fd->ft->flags & FL_2STEP)? 2: 1;
906	i = fd->ft->sectrac * fd->ft->heads;
907	cylinder = bp->bio_pblkno / i;
908	descyl = cylinder * steptrac;
909	sec = bp->bio_pblkno % i;
910	nsect = i - sec;
911	head = sec / fd->ft->sectrac;
912	sec = sec % fd->ft->sectrac + 1;
913
914	/* If everything is going swimmingly, use multisector xfer */
915	if (fdc->retry == 0 && bp->bio_cmd & (BIO_READ|BIO_WRITE)) {
916		fd->fd_iosize = imin(nsect * fd->sectorsize, bp->bio_resid);
917		nsect = fd->fd_iosize / fd->sectorsize;
918	} else if (bp->bio_cmd & (BIO_READ|BIO_WRITE)) {
919		fd->fd_iosize = fd->sectorsize;
920		nsect = 1;
921	}
922
923	/* Do RECAL if we need to or are going to track zero anyway */
924	if ((need_recal & (1 << fd->fdsu)) ||
925	    (cylinder == 0 && fd->track != 0) ||
926	    fdc->retry > 2) {
927		retry_line = __LINE__;
928		if (fdc_cmd(fdc, 2, NE7CMD_RECAL, fd->fdsu, 0))
929			return (1);
930		msleep(fdc, NULL, PRIBIO, "fdrecal", hz);
931		retry_line = __LINE__;
932		if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
933			return (1); /* XXX */
934		retry_line = __LINE__;
935		if ((st0 & 0xc0) || cyl != 0)
936			return (1);
937		need_recal &= ~(1 << fd->fdsu);
938		fd->track = 0;
939		/* let the heads settle */
940		if (settle)
941			msleep(fdc->fd, NULL, PRIBIO, "fdhdstl", settle);
942	}
943
944	/*
945	 * SEEK to where we want to be
946	 *
947	 * Enhanced controllers do implied seeks for read&write as long as
948	 * we do not need multiple steps per track.
949	 */
950	if (cylinder != fd->track && (
951	    fdc->fdct != FDC_ENHANCED ||
952	    descyl != cylinder ||
953	    (bp->bio_cmd & (BIO_RDID|BIO_FMT)))) {
954		retry_line = __LINE__;
955		if (fdc_cmd(fdc, 3, NE7CMD_SEEK, fd->fdsu, descyl, 0))
956			return (1);
957		msleep(fdc, NULL, PRIBIO, "fdseek", hz);
958		retry_line = __LINE__;
959		if (fdc_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
960			return (1); /* XXX */
961		retry_line = __LINE__;
962		if ((st0 & 0xc0) || cyl != descyl) {
963			need_recal |= (1 << fd->fdsu);
964			return (1);
965		}
966		/* let the heads settle */
967		if (settle)
968			msleep(fdc->fd, NULL, PRIBIO, "fdhdstl", settle);
969	}
970	fd->track = cylinder;
971
972	if (debugflags & 8)
973		printf("op %x bn %ju siz %u ptr %p retry %d\n",
974		    bp->bio_cmd, bp->bio_pblkno, fd->fd_iosize,
975		    fd->fd_ioptr, fdc->retry);
976
977	/* Setup ISADMA if we need it and have it */
978	if ((bp->bio_cmd & (BIO_READ|BIO_WRITE|BIO_FMT))
979	     && !(fdc->flags & FDC_NODMA)) {
980		mtx_lock(&Giant);
981		isa_dmastart(
982		    bp->bio_cmd & BIO_READ ? ISADMA_READ : ISADMA_WRITE,
983		    fd->fd_ioptr, fd->fd_iosize, fdc->dmachan);
984		mtx_unlock(&Giant);
985		mtx_lock(&fdc->fdc_mtx);
986		fd->flags |= FD_ISADMA;
987		mtx_unlock(&fdc->fdc_mtx);
988	}
989
990	/* Do PIO if we have to */
991	if (fdc->flags & FDC_NODMA) {
992		if (bp->bio_cmd & (BIO_READ|BIO_WRITE|BIO_FMT))
993			fdbcdr_wr(fdc, 1, fd->fd_iosize);
994		if (bp->bio_cmd & (BIO_WRITE|BIO_FMT))
995			fdc_pio(fdc);
996	}
997
998	switch(bp->bio_cmd) {
999	case BIO_FMT:
1000		/* formatting */
1001		finfo = (struct fd_formb *)bp->bio_data;
1002		retry_line = __LINE__;
1003		if (fdc_cmd(fdc, 6,
1004		    NE7CMD_FORMAT | mfm,
1005		    head << 2 | fd->fdsu,
1006		    finfo->fd_formb_secshift,
1007		    finfo->fd_formb_nsecs,
1008		    finfo->fd_formb_gaplen,
1009		    finfo->fd_formb_fillbyte, 0))
1010			return (1);
1011		break;
1012	case BIO_RDID:
1013		retry_line = __LINE__;
1014		if (fdc_cmd(fdc, 2,
1015		    NE7CMD_READID | mfm,
1016		    head << 2 | fd->fdsu, 0))
1017			return (1);
1018		break;
1019	case BIO_READ:
1020		retry_line = __LINE__;
1021		if (fdc_cmd(fdc, 9,
1022		    NE7CMD_READ | NE7CMD_SK | mfm | NE7CMD_MT,
1023		    head << 2 | fd->fdsu,	/* head & unit */
1024		    fd->track,			/* track */
1025		    head,			/* head */
1026		    sec,			/* sector + 1 */
1027		    fd->ft->secsize,		/* sector size */
1028		    fd->ft->sectrac,		/* sectors/track */
1029		    fd->ft->gap,		/* gap size */
1030		    fd->ft->datalen,		/* data length */
1031		    0))
1032			return (1);
1033		break;
1034	case BIO_WRITE:
1035		retry_line = __LINE__;
1036		if (fdc_cmd(fdc, 9,
1037		    NE7CMD_WRITE | mfm | NE7CMD_MT,
1038		    head << 2 | fd->fdsu,	/* head & unit */
1039		    fd->track,			/* track */
1040		    head,			/* head */
1041		    sec,			/* sector + 1 */
1042		    fd->ft->secsize,		/* sector size */
1043		    fd->ft->sectrac,		/* sectors/track */
1044		    fd->ft->gap,		/* gap size */
1045		    fd->ft->datalen,		/* data length */
1046		    0))
1047			return (1);
1048		break;
1049	default:
1050		KASSERT(0 == 1, ("Wrong bio_cmd %x\n", bp->bio_cmd));
1051	}
1052
1053	/* Wait for interrupt */
1054	i = msleep(fdc, NULL, PRIBIO, "fddata", hz);
1055
1056	/* PIO if the read looks good */
1057	if (i == 0 && (fdc->flags & FDC_NODMA) && (bp->bio_cmd & BIO_READ))
1058		fdc_pio(fdc);
1059
1060	/* Finish DMA */
1061	if (fd->flags & FD_ISADMA) {
1062		mtx_lock(&Giant);
1063		isa_dmadone(
1064		    bp->bio_cmd & BIO_READ ? ISADMA_READ : ISADMA_WRITE,
1065		    fd->fd_ioptr, fd->fd_iosize, fdc->dmachan);
1066		mtx_unlock(&Giant);
1067		mtx_lock(&fdc->fdc_mtx);
1068		fd->flags &= ~FD_ISADMA;
1069		mtx_unlock(&fdc->fdc_mtx);
1070	}
1071
1072	if (i != 0) {
1073		/*
1074		 * Timeout.
1075		 *
1076		 * Due to IBM's brain-dead design, the FDC has a faked ready
1077		 * signal, hardwired to ready == true. Thus, any command
1078		 * issued if there's no diskette in the drive will _never_
1079		 * complete, and must be aborted by resetting the FDC.
1080		 * Many thanks, Big Blue!
1081		 */
1082		retry_line = __LINE__;
1083		fdc->flags |= FDC_NEEDS_RESET;
1084		return (1);
1085	}
1086
1087	retry_line = __LINE__;
1088	if (fdc_read_status(fdc))
1089		return (1);
1090
1091	if (debugflags & 0x10)
1092		printf("  -> %x %x %x %x\n",
1093		    fdc->status[0], fdc->status[1],
1094		    fdc->status[2], fdc->status[3]);
1095
1096	st0 = fdc->status[0] & NE7_ST0_IC;
1097	if (st0 != 0) {
1098		retry_line = __LINE__;
1099		if (st0 == NE7_ST0_IC_AT && fdc->status[1] & NE7_ST1_OR) {
1100			/*
1101			 * DMA overrun. Someone hogged the bus and
1102			 * didn't release it in time for the next
1103			 * FDC transfer.
1104			 */
1105			return (1);
1106		}
1107		retry_line = __LINE__;
1108		if(st0 == NE7_ST0_IC_IV) {
1109			fdc->flags |= FDC_NEEDS_RESET;
1110			return (1);
1111		}
1112		retry_line = __LINE__;
1113		if(st0 == NE7_ST0_IC_AT && fdc->status[2] & NE7_ST2_WC) {
1114			need_recal |= (1 << fd->fdsu);
1115			return (1);
1116		}
1117		if (debugflags & 0x20) {
1118			printf("status %02x %02x %02x %02x %02x %02x\n",
1119			    fdc->status[0], fdc->status[1], fdc->status[2],
1120			    fdc->status[3], fdc->status[4], fdc->status[5]);
1121		}
1122		retry_line = __LINE__;
1123		return (1);
1124	}
1125	/* All OK */
1126	switch(bp->bio_cmd) {
1127	case BIO_RDID:
1128		/* copy out ID field contents */
1129		idp = (struct fdc_readid *)bp->bio_data;
1130		idp->cyl = fdc->status[3];
1131		idp->head = fdc->status[4];
1132		idp->sec = fdc->status[5];
1133		idp->secshift = fdc->status[6];
1134		if (debugflags & 0x40)
1135			printf("c %d h %d s %d z %d\n",
1136			    idp->cyl, idp->head, idp->sec, idp->secshift);
1137		break;
1138	case BIO_READ:
1139	case BIO_WRITE:
1140		bp->bio_pblkno += nsect;
1141		bp->bio_resid -= fd->fd_iosize;
1142		bp->bio_completed += fd->fd_iosize;
1143		fd->fd_ioptr += fd->fd_iosize;
1144		/* Since we managed to get something done, reset the retry */
1145		fdc->retry = 0;
1146		if (bp->bio_resid > 0)
1147			return (0);
1148		break;
1149	case BIO_FMT:
1150		break;
1151	}
1152	return (fdc_biodone(fdc, 0));
1153}
1154
1155static void
1156fdc_thread(void *arg)
1157{
1158	struct fdc_data *fdc;
1159
1160	fdc = arg;
1161	int i;
1162
1163	mtx_lock(&fdc->fdc_mtx);
1164	fdc->flags |= FDC_KTHREAD_ALIVE;
1165	while ((fdc->flags & FDC_KTHREAD_EXIT) == 0) {
1166		mtx_unlock(&fdc->fdc_mtx);
1167		i = fdc_worker(fdc);
1168		if (i && debugflags & 0x20) {
1169			if (fdc->bp != NULL) {
1170				g_print_bio(fdc->bp);
1171				printf("\n");
1172			}
1173			printf("Retry line %d\n", retry_line);
1174		}
1175		fdc->retry += i;
1176		mtx_lock(&fdc->fdc_mtx);
1177	}
1178	fdc->flags &= ~(FDC_KTHREAD_EXIT | FDC_KTHREAD_ALIVE);
1179	wakeup(&fdc->fdc_thread);
1180	mtx_unlock(&fdc->fdc_mtx);
1181
1182	kthread_exit(0);
1183}
1184
1185/*
1186 * Enqueue a request.
1187 */
1188static void
1189fd_enqueue(struct fd_data *fd, struct bio *bp)
1190{
1191	struct fdc_data *fdc;
1192	int call;
1193
1194	call = 0;
1195	fdc = fd->fdc;
1196	mtx_lock(&fdc->fdc_mtx);
1197	/* If we go from idle, cancel motor turnoff */
1198	if (fd->fd_iocount++ == 0)
1199		callout_drain(&fd->toffhandle);
1200	if (fd->flags & FD_MOTOR) {
1201		/* The motor is on, send it directly to the controller */
1202		bioq_disksort(&fdc->head, bp);
1203		wakeup(&fdc->head);
1204	} else {
1205		/* Queue it on the drive until the motor has started */
1206		bioq_insert_tail(&fd->fd_bq, bp);
1207		if (!(fd->flags & FD_MOTORWAIT))
1208			fd_motor(fd, 1);
1209	}
1210	mtx_unlock(&fdc->fdc_mtx);
1211}
1212
1213static int
1214fdmisccmd(struct fd_data *fd, u_int cmd, void *data)
1215{
1216	struct bio *bp;
1217	struct fd_formb *finfo;
1218	struct fdc_readid *idfield;
1219	int error;
1220
1221	bp = malloc(sizeof(struct bio), M_TEMP, M_WAITOK | M_ZERO);
1222
1223	/*
1224	 * Set up a bio request for fdstrategy().  bio_offset is faked
1225	 * so that fdstrategy() will seek to the the requested
1226	 * cylinder, and use the desired head.
1227	 */
1228	bp->bio_cmd = cmd;
1229	if (cmd == BIO_FMT) {
1230		finfo = (struct fd_formb *)data;
1231		bp->bio_pblkno =
1232		    (finfo->cyl * fd->ft->heads + finfo->head) *
1233		    fd->ft->sectrac;
1234		bp->bio_length = sizeof *finfo;
1235	} else if (cmd == BIO_RDID) {
1236		idfield = (struct fdc_readid *)data;
1237		bp->bio_pblkno =
1238		    (idfield->cyl * fd->ft->heads + idfield->head) *
1239		    fd->ft->sectrac;
1240		bp->bio_length = sizeof(struct fdc_readid);
1241	} else if (cmd == BIO_PROBE) {
1242		/* nothing */
1243	} else
1244		panic("wrong cmd in fdmisccmd()");
1245	bp->bio_offset = bp->bio_pblkno * fd->sectorsize;
1246	bp->bio_data = data;
1247	bp->bio_driver1 = fd;
1248	bp->bio_flags = 0;
1249
1250	fd_enqueue(fd, bp);
1251
1252	do {
1253		msleep(bp, NULL, PRIBIO, "fdwait", hz);
1254	} while (!(bp->bio_flags & BIO_DONE));
1255	error = bp->bio_error;
1256
1257	free(bp, M_TEMP);
1258	return (error);
1259}
1260
1261/*
1262 * Try figuring out the density of the media present in our device.
1263 */
1264static int
1265fdautoselect(struct fd_data *fd)
1266{
1267	struct fd_type *fdtp;
1268	struct fdc_readid id;
1269	int oopts, rv;
1270
1271	if (!(fd->ft->flags & FL_AUTO))
1272		return (0);
1273
1274	fdtp = fd_native_types[fd->type];
1275	fdsettype(fd, fdtp);
1276	if (!(fd->ft->flags & FL_AUTO))
1277		return (0);
1278
1279	/*
1280	 * Try reading sector ID fields, first at cylinder 0, head 0,
1281	 * then at cylinder 2, head N.  We don't probe cylinder 1,
1282	 * since for 5.25in DD media in a HD drive, there are no data
1283	 * to read (2 step pulses per media cylinder required).  For
1284	 * two-sided media, the second probe always goes to head 1, so
1285	 * we can tell them apart from single-sided media.  As a
1286	 * side-effect this means that single-sided media should be
1287	 * mentioned in the search list after two-sided media of an
1288	 * otherwise identical density.  Media with a different number
1289	 * of sectors per track but otherwise identical parameters
1290	 * cannot be distinguished at all.
1291	 *
1292	 * If we successfully read an ID field on both cylinders where
1293	 * the recorded values match our expectation, we are done.
1294	 * Otherwise, we try the next density entry from the table.
1295	 *
1296	 * Stepping to cylinder 2 has the side-effect of clearing the
1297	 * unit attention bit.
1298	 */
1299	oopts = fd->options;
1300	fd->options |= FDOPT_NOERRLOG | FDOPT_NORETRY;
1301	for (; fdtp->heads; fdtp++) {
1302		fdsettype(fd, fdtp);
1303
1304		id.cyl = id.head = 0;
1305		rv = fdmisccmd(fd, BIO_RDID, &id);
1306		if (rv != 0)
1307			continue;
1308		if (id.cyl != 0 || id.head != 0 || id.secshift != fdtp->secsize)
1309			continue;
1310		id.cyl = 2;
1311		id.head = fd->ft->heads - 1;
1312		rv = fdmisccmd(fd, BIO_RDID, &id);
1313		if (id.cyl != 2 || id.head != fdtp->heads - 1 ||
1314		    id.secshift != fdtp->secsize)
1315			continue;
1316		if (rv == 0)
1317			break;
1318	}
1319
1320	fd->options = oopts;
1321	if (fdtp->heads == 0) {
1322		if (debugflags & 0x40)
1323			device_printf(fd->dev, "autoselection failed\n");
1324		fdsettype(fd, fd_native_types[fd->type]);
1325		return (0);
1326	} else {
1327		if (debugflags & 0x40) {
1328			device_printf(fd->dev,
1329			    "autoselected %d KB medium\n", fd->ft->size / 2);
1330			fdprinttype(fd->ft);
1331		}
1332		return (0);
1333	}
1334}
1335
1336/*
1337 * GEOM class implementation
1338 */
1339
1340static g_access_t	fd_access;
1341static g_start_t	fd_start;
1342static g_ioctl_t	fd_ioctl;
1343
1344struct g_class g_fd_class = {
1345	.name =		"FD",
1346	.version =	G_VERSION,
1347	.start =	fd_start,
1348	.access =	fd_access,
1349	.ioctl =	fd_ioctl,
1350};
1351
1352static int
1353fd_access(struct g_provider *pp, int r, int w, int e)
1354{
1355	struct fd_data *fd;
1356	struct fdc_data *fdc;
1357	int ar, aw, ae;
1358
1359	fd = pp->geom->softc;
1360	fdc = fd->fdc;
1361
1362	/*
1363	 * If our provider is withering, we can only get negative requests
1364	 * and we don't want to even see them
1365	 */
1366	if (pp->flags & G_PF_WITHER)
1367		return (0);
1368
1369	ar = r + pp->acr;
1370	aw = w + pp->acw;
1371	ae = e + pp->ace;
1372
1373	if (ar == 0 && aw == 0 && ae == 0) {
1374		device_unbusy(fd->dev);
1375		return (0);
1376	}
1377
1378	if (pp->acr == 0 && pp->acw == 0 && pp->ace == 0) {
1379		if (fdmisccmd(fd, BIO_PROBE, NULL))
1380			return (ENXIO);
1381		if (fd->flags & FD_EMPTY)
1382			return (ENXIO);
1383		if (fd->flags & FD_NEWDISK) {
1384			fdautoselect(fd);
1385			mtx_lock(&fdc->fdc_mtx);
1386			fd->flags &= ~FD_NEWDISK;
1387			mtx_unlock(&fdc->fdc_mtx);
1388		}
1389		device_busy(fd->dev);
1390	}
1391
1392	if (w > 0 && (fd->flags & FD_WP))
1393		return (EROFS);
1394
1395	pp->sectorsize = fd->sectorsize;
1396	pp->stripesize = fd->ft->heads * fd->ft->sectrac * fd->sectorsize;
1397	pp->mediasize = pp->stripesize * fd->ft->tracks;
1398	return (0);
1399}
1400
1401static void
1402fd_start(struct bio *bp)
1403{
1404 	struct fdc_data *	fdc;
1405 	struct fd_data *	fd;
1406
1407	fd = bp->bio_to->geom->softc;
1408	fdc = fd->fdc;
1409	bp->bio_driver1 = fd;
1410	if (bp->bio_cmd & BIO_GETATTR) {
1411		if (g_handleattr_int(bp, "GEOM::fwsectors", fd->ft->sectrac))
1412			return;
1413		if (g_handleattr_int(bp, "GEOM::fwheads", fd->ft->heads))
1414			return;
1415		g_io_deliver(bp, ENOIOCTL);
1416		return;
1417	}
1418	if (!(bp->bio_cmd & (BIO_READ|BIO_WRITE))) {
1419		g_io_deliver(bp, EOPNOTSUPP);
1420		return;
1421	}
1422	bp->bio_pblkno = bp->bio_offset / fd->sectorsize;
1423	bp->bio_resid = bp->bio_length;
1424	fd_enqueue(fd, bp);
1425	return;
1426}
1427
1428static int
1429fd_ioctl(struct g_provider *pp, u_long cmd, void *data, int fflag, struct thread *td)
1430{
1431	struct fd_data *fd;
1432	struct fdc_status *fsp;
1433	struct fdc_readid *rid;
1434	int error;
1435
1436	fd = pp->geom->softc;
1437
1438	switch (cmd) {
1439	case FD_GTYPE:                  /* get drive type */
1440		*(struct fd_type *)data = *fd->ft;
1441		return (0);
1442
1443	case FD_STYPE:                  /* set drive type */
1444		if (!fflag & FWRITE)
1445			return (EPERM);
1446		/*
1447		 * Allow setting drive type temporarily iff
1448		 * currently unset.  Used for fdformat so any
1449		 * user can set it, and then start formatting.
1450		 */
1451		fd->fts = *(struct fd_type *)data;
1452		if (fd->fts.sectrac) {
1453			/* XXX: check for rubbish */
1454			fdsettype(fd, &fd->fts);
1455		} else {
1456			fdsettype(fd, fd_native_types[fd->type]);
1457		}
1458		if (debugflags & 0x40)
1459			fdprinttype(fd->ft);
1460		return (0);
1461
1462	case FD_GOPTS:			/* get drive options */
1463		*(int *)data = fd->options;
1464		return (0);
1465
1466	case FD_SOPTS:			/* set drive options */
1467		if (!fflag & FWRITE)
1468			return (EPERM);
1469		fd->options = *(int *)data;
1470		return (0);
1471
1472	case FD_CLRERR:
1473		if (suser(td) != 0)
1474			return (EPERM);
1475		fd->fdc->fdc_errs = 0;
1476		return (0);
1477
1478	case FD_GSTAT:
1479		fsp = (struct fdc_status *)data;
1480		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
1481			return (EINVAL);
1482		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
1483		return (0);
1484
1485	case FD_GDTYPE:
1486		*(enum fd_drivetype *)data = fd->type;
1487		return (0);
1488
1489	case FD_FORM:
1490		if (!fflag & FWRITE)
1491			return (EPERM);
1492		if (((struct fd_formb *)data)->format_version !=
1493		    FD_FORMAT_VERSION)
1494			return (EINVAL); /* wrong version of formatting prog */
1495		error = fdmisccmd(fd, BIO_FMT, data);
1496		mtx_lock(&fd->fdc->fdc_mtx);
1497		fd->flags |= FD_NEWDISK;
1498		mtx_unlock(&fd->fdc->fdc_mtx);
1499		break;
1500
1501	case FD_READID:
1502		rid = (struct fdc_readid *)data;
1503		if (rid->cyl > 85 || rid->head > 1)
1504			return (EINVAL);
1505		error = fdmisccmd(fd, BIO_RDID, data);
1506		break;
1507
1508	case FIONBIO:
1509	case FIOASYNC:
1510		/* For backwards compat with old fd*(8) tools */
1511		error = 0;
1512		break;
1513
1514	default:
1515		if (debugflags & 0x80)
1516			printf("Unknown ioctl %lx\n", cmd);
1517		error = ENOIOCTL;
1518		break;
1519	}
1520	return (error);
1521};
1522
1523
1524
1525/*
1526 * Configuration/initialization stuff, per controller.
1527 */
1528
1529devclass_t fdc_devclass;
1530static devclass_t fd_devclass;
1531
1532struct fdc_ivars {
1533	int	fdunit;
1534	int	fdtype;
1535};
1536
1537void
1538fdc_release_resources(struct fdc_data *fdc)
1539{
1540	device_t dev;
1541	struct resource *last;
1542	int i;
1543
1544	dev = fdc->fdc_dev;
1545	if (fdc->fdc_intr)
1546		bus_teardown_intr(dev, fdc->res_irq, fdc->fdc_intr);
1547	fdc->fdc_intr = NULL;
1548	if (fdc->res_irq != NULL)
1549		bus_release_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
1550		    fdc->res_irq);
1551	fdc->res_irq = NULL;
1552	last = NULL;
1553	for (i = 0; i < FDC_MAXREG; i++) {
1554		if (fdc->resio[i] != NULL && fdc->resio[i] != last) {
1555			bus_release_resource(dev, SYS_RES_IOPORT,
1556			    fdc->ridio[i], fdc->resio[i]);
1557			last = fdc->resio[i];
1558			fdc->resio[i] = NULL;
1559		}
1560	}
1561	if (fdc->res_drq != NULL)
1562		bus_release_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
1563		    fdc->res_drq);
1564	fdc->res_drq = NULL;
1565}
1566
1567int
1568fdc_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1569{
1570	struct fdc_ivars *ivars = device_get_ivars(child);
1571
1572	switch (which) {
1573	case FDC_IVAR_FDUNIT:
1574		*result = ivars->fdunit;
1575		break;
1576	case FDC_IVAR_FDTYPE:
1577		*result = ivars->fdtype;
1578		break;
1579	default:
1580		return (ENOENT);
1581	}
1582	return (0);
1583}
1584
1585int
1586fdc_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1587{
1588	struct fdc_ivars *ivars = device_get_ivars(child);
1589
1590	switch (which) {
1591	case FDC_IVAR_FDUNIT:
1592		ivars->fdunit = value;
1593		break;
1594	case FDC_IVAR_FDTYPE:
1595		ivars->fdtype = value;
1596		break;
1597	default:
1598		return (ENOENT);
1599	}
1600	return (0);
1601}
1602
1603int
1604fdc_initial_reset(device_t dev, struct fdc_data *fdc)
1605{
1606	int ic_type, part_id;
1607
1608	/*
1609	 * A status value of 0xff is very unlikely, but not theoretically
1610	 * impossible, but it is far more likely to indicate an empty bus.
1611	 */
1612	if (fdsts_rd(fdc) == 0xff)
1613		return (ENXIO);
1614
1615	/*
1616	 * Assert a reset to the floppy controller and check that the status
1617	 * register goes to zero.
1618	 */
1619	fdout_wr(fdc, 0);
1620	fdout_wr(fdc, 0);
1621	if (fdsts_rd(fdc) != 0)
1622		return (ENXIO);
1623
1624	/*
1625	 * Clear the reset and see it come ready.
1626	 */
1627	fdout_wr(fdc, FDO_FRST);
1628	DELAY(100);
1629	if (fdsts_rd(fdc) != 0x80)
1630		return (ENXIO);
1631
1632	/* Then, see if it can handle a command. */
1633	if (fdc_cmd(fdc, 3, NE7CMD_SPECIFY, 0xaf, 0x1e, 0))
1634		return (ENXIO);
1635
1636	/*
1637	 * Try to identify the chip.
1638	 *
1639	 * The i8272 datasheet documents that unknown commands
1640	 * will return ST0 as 0x80.  The i8272 is supposedly identical
1641	 * to the NEC765.
1642	 * The i82077SL datasheet says 0x90 for the VERSION command,
1643	 * and several "superio" chips emulate this.
1644	 */
1645	if (fdc_cmd(fdc, 1, NE7CMD_VERSION, 1, &ic_type))
1646		return (ENXIO);
1647	if (fdc_cmd(fdc, 1, 0x18, 1, &part_id))
1648		return (ENXIO);
1649	if (bootverbose)
1650		device_printf(dev,
1651		    "ic_type %02x part_id %02x\n", ic_type, part_id);
1652	switch (ic_type & 0xff) {
1653	case 0x80:
1654		device_set_desc(dev, "NEC 765 or clone");
1655		fdc->fdct = FDC_NE765;
1656		break;
1657	case 0x81:
1658	case 0x90:
1659		device_set_desc(dev,
1660		    "Enhanced floppy controller");
1661		fdc->fdct = FDC_ENHANCED;
1662		break;
1663	default:
1664		device_set_desc(dev, "Generic floppy controller");
1665		fdc->fdct = FDC_UNKNOWN;
1666		break;
1667	}
1668	return (0);
1669}
1670
1671int
1672fdc_detach(device_t dev)
1673{
1674	struct	fdc_data *fdc;
1675	int	error;
1676
1677	fdc = device_get_softc(dev);
1678
1679	/* have our children detached first */
1680	if ((error = bus_generic_detach(dev)))
1681		return (error);
1682
1683	/* kill worker thread */
1684	fdc->flags |= FDC_KTHREAD_EXIT;
1685	mtx_lock(&fdc->fdc_mtx);
1686	wakeup(&fdc->head);
1687	while ((fdc->flags & FDC_KTHREAD_ALIVE) != 0)
1688		msleep(&fdc->fdc_thread, &fdc->fdc_mtx, PRIBIO, "fdcdet", 0);
1689	mtx_unlock(&fdc->fdc_mtx);
1690
1691	/* reset controller, turn motor off */
1692	fdout_wr(fdc, 0);
1693
1694	if (!(fdc->flags & FDC_NODMA))
1695		isa_dma_release(fdc->dmachan);
1696	fdc_release_resources(fdc);
1697	mtx_destroy(&fdc->fdc_mtx);
1698	return (0);
1699}
1700
1701/*
1702 * Add a child device to the fdc controller.  It will then be probed etc.
1703 */
1704device_t
1705fdc_add_child(device_t dev, const char *name, int unit)
1706{
1707	struct fdc_ivars *ivar;
1708	device_t child;
1709
1710	ivar = malloc(sizeof *ivar, M_DEVBUF /* XXX */, M_NOWAIT | M_ZERO);
1711	if (ivar == NULL)
1712		return (NULL);
1713	child = device_add_child(dev, name, unit);
1714	if (child == NULL) {
1715		free(ivar, M_DEVBUF);
1716		return (NULL);
1717	}
1718	device_set_ivars(child, ivar);
1719	ivar->fdunit = unit;
1720	ivar->fdtype = FDT_NONE;
1721	if (resource_disabled(name, unit))
1722		device_disable(child);
1723	return (child);
1724}
1725
1726int
1727fdc_attach(device_t dev)
1728{
1729	struct	fdc_data *fdc;
1730	int	error;
1731
1732	fdc = device_get_softc(dev);
1733	fdc->fdc_dev = dev;
1734	error = fdc_initial_reset(dev, fdc);
1735	if (error) {
1736		device_printf(dev, "does not respond\n");
1737		return (error);
1738	}
1739	error = bus_setup_intr(dev, fdc->res_irq,
1740	    INTR_TYPE_BIO | INTR_ENTROPY | INTR_MPSAFE |
1741	    ((fdc->flags & FDC_NOFAST) ? 0 : INTR_FAST),
1742	    fdc_intr, fdc, &fdc->fdc_intr);
1743	if (error) {
1744		device_printf(dev, "cannot setup interrupt\n");
1745		return (error);
1746	}
1747	if (!(fdc->flags & FDC_NODMA)) {
1748		error = isa_dma_acquire(fdc->dmachan);
1749		if (!error) {
1750			error = isa_dma_init(fdc->dmachan,
1751			    MAX_BYTES_PER_CYL, M_WAITOK);
1752			if (error)
1753				isa_dma_release(fdc->dmachan);
1754		}
1755		if (error)
1756			return (error);
1757	}
1758	fdc->fdcu = device_get_unit(dev);
1759	fdc->flags |= FDC_NEEDS_RESET;
1760
1761	mtx_init(&fdc->fdc_mtx, "fdc lock", NULL, MTX_DEF);
1762
1763	/* reset controller, turn motor off, clear fdout mirror reg */
1764	fdout_wr(fdc, fdc->fdout = 0);
1765	bioq_init(&fdc->head);
1766
1767	kthread_create(fdc_thread, fdc, &fdc->fdc_thread, 0, 0,
1768	    "fdc%d", device_get_unit(dev));
1769
1770	settle = hz / 8;
1771
1772	return (0);
1773}
1774
1775int
1776fdc_hints_probe(device_t dev)
1777{
1778	const char *name, *dname;
1779	int i, error, dunit;
1780
1781	/*
1782	 * Probe and attach any children.  We should probably detect
1783	 * devices from the BIOS unless overridden.
1784	 */
1785	name = device_get_nameunit(dev);
1786	i = 0;
1787	while ((resource_find_match(&i, &dname, &dunit, "at", name)) == 0) {
1788		resource_int_value(dname, dunit, "drive", &dunit);
1789		fdc_add_child(dev, dname, dunit);
1790	}
1791
1792	if ((error = bus_generic_attach(dev)) != 0)
1793		return (error);
1794	return (0);
1795}
1796
1797int
1798fdc_print_child(device_t me, device_t child)
1799{
1800	int retval = 0, flags;
1801
1802	retval += bus_print_child_header(me, child);
1803	retval += printf(" on %s drive %d", device_get_nameunit(me),
1804	       fdc_get_fdunit(child));
1805	if ((flags = device_get_flags(me)) != 0)
1806		retval += printf(" flags %#x", flags);
1807	retval += printf("\n");
1808
1809	return (retval);
1810}
1811
1812/*
1813 * Configuration/initialization, per drive.
1814 */
1815static int
1816fd_probe(device_t dev)
1817{
1818	int	i, unit;
1819	u_int	st0, st3;
1820	struct	fd_data *fd;
1821	struct	fdc_data *fdc;
1822	int	fdsu;
1823	int	flags, type;
1824
1825	fdsu = fdc_get_fdunit(dev);
1826	fd = device_get_softc(dev);
1827	fdc = device_get_softc(device_get_parent(dev));
1828	flags = device_get_flags(dev);
1829
1830	fd->dev = dev;
1831	fd->fdc = fdc;
1832	fd->fdsu = fdsu;
1833	unit = device_get_unit(dev);
1834
1835	/* Auto-probe if fdinfo is present, but always allow override. */
1836	type = flags & FD_TYPEMASK;
1837	if (type == FDT_NONE && (type = fdc_get_fdtype(dev)) != FDT_NONE) {
1838		fd->type = type;
1839		goto done;
1840	} else {
1841		/* make sure fdautoselect() will be called */
1842		fd->flags = FD_EMPTY;
1843		fd->type = type;
1844	}
1845
1846#if (defined(__i386__) && !defined(PC98)) || defined(__amd64__)
1847	if (fd->type == FDT_NONE && (unit == 0 || unit == 1)) {
1848		/* Look up what the BIOS thinks we have. */
1849		if (unit == 0)
1850			fd->type = (rtcin(RTC_FDISKETTE) & 0xf0) >> 4;
1851		else
1852			fd->type = rtcin(RTC_FDISKETTE) & 0x0f;
1853		if (fd->type == FDT_288M_1)
1854			fd->type = FDT_288M;
1855	}
1856#endif /* __i386__ || __amd64__ */
1857	/* is there a unit? */
1858	if (fd->type == FDT_NONE)
1859		return (ENXIO);
1860
1861/*
1862	mtx_lock(&fdc->fdc_mtx);
1863*/
1864	/* select it */
1865	fd_select(fd);
1866	fd_motor(fd, 1);
1867	fdc->fd = fd;
1868	fdc_reset(fdc);		/* XXX reset, then unreset, etc. */
1869	DELAY(1000000);	/* 1 sec */
1870
1871	if ((flags & FD_NO_PROBE) == 0) {
1872		/* If we're at track 0 first seek inwards. */
1873		if ((fdc_sense_drive(fdc, &st3) == 0) &&
1874		    (st3 & NE7_ST3_T0)) {
1875			/* Seek some steps... */
1876			if (fdc_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1877				/* ...wait a moment... */
1878				DELAY(300000);
1879				/* make ctrlr happy: */
1880				fdc_sense_int(fdc, 0, 0);
1881			}
1882		}
1883
1884		for (i = 0; i < 2; i++) {
1885			/*
1886			 * we must recalibrate twice, just in case the
1887			 * heads have been beyond cylinder 76, since
1888			 * most FDCs still barf when attempting to
1889			 * recalibrate more than 77 steps
1890			 */
1891			/* go back to 0: */
1892			if (fdc_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1893				/* a second being enough for full stroke seek*/
1894				DELAY(i == 0 ? 1000000 : 300000);
1895
1896				/* anything responding? */
1897				if (fdc_sense_int(fdc, &st0, 0) == 0 &&
1898				    (st0 & NE7_ST0_EC) == 0)
1899					break; /* already probed succesfully */
1900			}
1901		}
1902	}
1903
1904	fd_motor(fd, 0);
1905	fdc->fd = NULL;
1906/*
1907	mtx_unlock(&fdc->fdc_mtx);
1908*/
1909
1910	if ((flags & FD_NO_PROBE) == 0 &&
1911	    (st0 & NE7_ST0_EC) != 0) /* no track 0 -> no drive present */
1912		return (ENXIO);
1913
1914done:
1915
1916	switch (fd->type) {
1917	case FDT_12M:
1918		device_set_desc(dev, "1200-KB 5.25\" drive");
1919		break;
1920	case FDT_144M:
1921		device_set_desc(dev, "1440-KB 3.5\" drive");
1922		break;
1923	case FDT_288M:
1924		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
1925		break;
1926	case FDT_360K:
1927		device_set_desc(dev, "360-KB 5.25\" drive");
1928		break;
1929	case FDT_720K:
1930		device_set_desc(dev, "720-KB 3.5\" drive");
1931		break;
1932	default:
1933		return (ENXIO);
1934	}
1935	fd->track = FD_NO_TRACK;
1936	fd->fdc = fdc;
1937	fd->fdsu = fdsu;
1938	fd->options = 0;
1939	callout_init(&fd->toffhandle, 1);
1940	callout_init(&fd->tohandle, 1);
1941
1942	/* initialize densities for subdevices */
1943	fdsettype(fd, fd_native_types[fd->type]);
1944	return (0);
1945}
1946
1947/*
1948 * We have to do this in a geom event because GEOM is not running
1949 * when fd_attach() is.
1950 * XXX: move fd_attach after geom like ata/scsi disks
1951 */
1952static void
1953fd_attach2(void *arg, int flag)
1954{
1955	struct	fd_data *fd;
1956
1957	fd = arg;
1958
1959	fd->fd_geom = g_new_geomf(&g_fd_class,
1960	    "fd%d", device_get_unit(fd->dev));
1961	fd->fd_provider = g_new_providerf(fd->fd_geom, fd->fd_geom->name);
1962	fd->fd_geom->softc = fd;
1963	g_error_provider(fd->fd_provider, 0);
1964}
1965
1966static int
1967fd_attach(device_t dev)
1968{
1969	struct	fd_data *fd;
1970
1971	fd = device_get_softc(dev);
1972	g_post_event(fd_attach2, fd, M_WAITOK, NULL);
1973	fd->flags |= FD_EMPTY;
1974	bioq_init(&fd->fd_bq);
1975
1976	return (0);
1977}
1978
1979static int
1980fd_detach(device_t dev)
1981{
1982	struct	fd_data *fd;
1983
1984	fd = device_get_softc(dev);
1985	g_topology_lock();
1986	g_wither_geom(fd->fd_geom, ENXIO);
1987	g_topology_unlock();
1988	while (device_get_state(dev) == DS_BUSY)
1989		tsleep(fd, PZERO, "fdd", hz/10);
1990	callout_drain(&fd->toffhandle);
1991
1992	return (0);
1993}
1994
1995static device_method_t fd_methods[] = {
1996	/* Device interface */
1997	DEVMETHOD(device_probe,		fd_probe),
1998	DEVMETHOD(device_attach,	fd_attach),
1999	DEVMETHOD(device_detach,	fd_detach),
2000	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
2001	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
2002	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
2003	{ 0, 0 }
2004};
2005
2006static driver_t fd_driver = {
2007	"fd",
2008	fd_methods,
2009	sizeof(struct fd_data)
2010};
2011
2012static int
2013fdc_modevent(module_t mod, int type, void *data)
2014{
2015
2016	g_modevent(NULL, type, &g_fd_class);
2017	return (0);
2018}
2019
2020DRIVER_MODULE(fd, fdc, fd_driver, fd_devclass, fdc_modevent, 0);
2021