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