fdc.c revision 125851
1/*
2 * Copyright (c) 1990 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Don Ahn.
7 *
8 * Libretto PCMCIA floppy support by David Horwitt (dhorwitt@ucsd.edu)
9 * aided by the Linux floppy driver modifications from David Bateman
10 * (dbateman@eng.uts.edu.au).
11 *
12 * Copyright (c) 1993, 1994 by
13 *  jc@irbs.UUCP (John Capo)
14 *  vak@zebub.msk.su (Serge Vakulenko)
15 *  ache@astral.msk.su (Andrew A. Chernov)
16 *
17 * Copyright (c) 1993, 1994, 1995 by
18 *  joerg_wunsch@uriah.sax.de (Joerg Wunsch)
19 *  dufault@hda.com (Peter Dufault)
20 *
21 * Copyright (c) 2001 Joerg Wunsch,
22 *  joerg_wunsch@uriah.heep.sax.de (Joerg Wunsch)
23 *
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
26 * are met:
27 * 1. Redistributions of source code must retain the above copyright
28 *    notice, this list of conditions and the following disclaimer.
29 * 2. Redistributions in binary form must reproduce the above copyright
30 *    notice, this list of conditions and the following disclaimer in the
31 *    documentation and/or other materials provided with the distribution.
32 * 3. All advertising materials mentioning features or use of this software
33 *    must display the following acknowledgement:
34 *	This product includes software developed by the University of
35 *	California, Berkeley and its contributors.
36 * 4. Neither the name of the University nor the names of its contributors
37 *    may be used to endorse or promote products derived from this software
38 *    without specific prior written permission.
39 *
40 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 *	from:	@(#)fd.c	7.4 (Berkeley) 5/25/91
53 */
54
55#include <sys/cdefs.h>
56__FBSDID("$FreeBSD: head/sys/dev/fdc/fdc.c 125851 2004-02-15 20:30:22Z njl $");
57
58#include "opt_fdc.h"
59#include "card.h"
60
61#include <sys/param.h>
62#include <sys/systm.h>
63#include <sys/bio.h>
64#include <sys/bus.h>
65#include <sys/conf.h>
66#include <sys/devicestat.h>
67#include <sys/disk.h>
68#include <sys/fcntl.h>
69#include <sys/fdcio.h>
70#include <sys/filio.h>
71#include <sys/kernel.h>
72#include <sys/lock.h>
73#include <sys/malloc.h>
74#include <sys/module.h>
75#include <sys/mutex.h>
76#include <sys/proc.h>
77#include <sys/syslog.h>
78
79#include <machine/bus.h>
80#include <sys/rman.h>
81
82#include <machine/clock.h>
83#include <machine/resource.h>
84#include <machine/stdarg.h>
85
86#include <isa/isavar.h>
87#include <isa/isareg.h>
88#include <isa/fdreg.h>
89#include <isa/rtc.h>
90
91enum fdc_type
92{
93	FDC_NE765, FDC_ENHANCED, FDC_UNKNOWN = -1
94};
95
96enum fdc_states {
97	DEVIDLE,
98	FINDWORK,
99	DOSEEK,
100	SEEKCOMPLETE ,
101	IOCOMPLETE,
102	RECALCOMPLETE,
103	STARTRECAL,
104	RESETCTLR,
105	SEEKWAIT,
106	RECALWAIT,
107	MOTORWAIT,
108	IOTIMEDOUT,
109	RESETCOMPLETE,
110	PIOREAD
111};
112
113#ifdef	FDC_DEBUG
114static char const * const fdstates[] = {
115	"DEVIDLE",
116	"FINDWORK",
117	"DOSEEK",
118	"SEEKCOMPLETE",
119	"IOCOMPLETE",
120	"RECALCOMPLETE",
121	"STARTRECAL",
122	"RESETCTLR",
123	"SEEKWAIT",
124	"RECALWAIT",
125	"MOTORWAIT",
126	"IOTIMEDOUT",
127	"RESETCOMPLETE",
128	"PIOREAD"
129};
130#endif
131
132/*
133 * Per controller structure (softc).
134 */
135struct fdc_data
136{
137	int	fdcu;		/* our unit number */
138	int	dmachan;
139	int	flags;
140#define FDC_ATTACHED	0x01
141#define FDC_STAT_VALID	0x08
142#define FDC_HAS_FIFO	0x10
143#define FDC_NEEDS_RESET	0x20
144#define FDC_NODMA	0x40
145#define FDC_ISPNP	0x80
146#define FDC_ISPCMCIA	0x100
147	struct	fd_data *fd;
148	int	fdu;		/* the active drive	*/
149	enum	fdc_states state;
150	int	retry;
151	int	fdout;		/* mirror of the w/o digital output reg */
152	u_int	status[7];	/* copy of the registers */
153	enum	fdc_type fdct;	/* chip version of FDC */
154	int	fdc_errs;	/* number of logged errors */
155	int	dma_overruns;	/* number of DMA overruns */
156	struct	bio_queue_head head;
157	struct	bio *bp;	/* active buffer */
158	struct	resource *res_ioport, *res_ctl, *res_irq, *res_drq;
159	int	rid_ioport, rid_ctl, rid_irq, rid_drq;
160	int	port_off;
161	bus_space_tag_t portt;
162	bus_space_handle_t porth;
163	bus_space_tag_t ctlt;
164	bus_space_handle_t ctlh;
165	void	*fdc_intr;
166	struct	device *fdc_dev;
167	void	(*fdctl_wr)(struct fdc_data *fdc, u_int8_t v);
168};
169
170#define FDBIO_FORMAT	BIO_CMD2
171
172typedef int	fdu_t;
173typedef int	fdcu_t;
174typedef int	fdsu_t;
175typedef	struct fd_data *fd_p;
176typedef struct fdc_data *fdc_p;
177typedef enum fdc_type fdc_t;
178
179#define FDUNIT(s)	(((s) >> 6) & 3)
180#define FDNUMTOUNIT(n)	(((n) & 3) << 6)
181#define FDTYPE(s)	((s) & 0x3f)
182
183/*
184 * fdc maintains a set (1!) of ivars per child of each controller.
185 */
186enum fdc_device_ivars {
187	FDC_IVAR_FDUNIT,
188};
189
190/*
191 * Simple access macros for the ivars.
192 */
193#define FDC_ACCESSOR(A, B, T)						\
194static __inline T fdc_get_ ## A(device_t dev)				\
195{									\
196	uintptr_t v;							\
197	BUS_READ_IVAR(device_get_parent(dev), dev, FDC_IVAR_ ## B, &v);	\
198	return (T) v;							\
199}
200FDC_ACCESSOR(fdunit,	FDUNIT,	int)
201
202/* configuration flags for fdc */
203#define FDC_NO_FIFO	(1 << 2)	/* do not enable FIFO  */
204
205/* error returns for fd_cmd() */
206#define FD_FAILED -1
207#define FD_NOT_VALID -2
208#define FDC_ERRMAX	100	/* do not log more */
209/*
210 * Stop retrying after this many DMA overruns.  Since each retry takes
211 * one revolution, with 300 rpm., 25 retries take approximately 5
212 * seconds which the read attempt will block in case the DMA overrun
213 * is persistent.
214 */
215#define FDC_DMAOV_MAX	25
216
217/*
218 * Timeout value for the PIO loops to wait until the FDC main status
219 * register matches our expectations (request for master, direction
220 * bit).  This is supposed to be a number of microseconds, although
221 * timing might actually not be very accurate.
222 *
223 * Timeouts of 100 msec are believed to be required for some broken
224 * (old) hardware.
225 */
226#define	FDSTS_TIMEOUT	100000
227
228/*
229 * Number of subdevices that can be used for different density types.
230 * By now, the lower 6 bit of the minor number are reserved for this,
231 * allowing for up to 64 subdevices, but we only use 16 out of this.
232 * Density #0 is used for automatic format detection, the other
233 * densities are available as programmable densities (for assignment
234 * by fdcontrol(8)).
235 * The upper 2 bits of the minor number are reserved for the subunit
236 * (drive #) per controller.
237 */
238#define NUMDENS		16
239
240#define FDBIO_RDSECTID	BIO_CMD1
241
242/*
243 * List of native drive densities.  Order must match enum fd_drivetype
244 * in <sys/fdcio.h>.  Upon attaching the drive, each of the
245 * programmable subdevices is initialized with the native density
246 * definition.
247 */
248static struct fd_type fd_native_types[] =
249{
250{ 0 },				/* FDT_NONE */
251{  9,2,0xFF,0x2A,40, 720,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* FDT_360K */
252{ 15,2,0xFF,0x1B,80,2400,FDC_500KBPS,2,0x54,1,0,FL_MFM }, /* FDT_12M  */
253{  9,2,0xFF,0x20,80,1440,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* FDT_720K */
254{ 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* FDT_144M */
255#if 0				/* we currently don't handle 2.88 MB */
256{ 36,2,0xFF,0x1B,80,5760,FDC_1MBPS,  2,0x4C,1,1,FL_MFM|FL_PERPND } /*FDT_288M*/
257#else
258{ 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* FDT_144M */
259#endif
260};
261
262/*
263 * 360 KB 5.25" and 720 KB 3.5" drives don't have automatic density
264 * selection, they just start out with their native density (or lose).
265 * So 1.2 MB 5.25", 1.44 MB 3.5", and 2.88 MB 3.5" drives have their
266 * respective lists of densities to search for.
267 */
268static struct fd_type fd_searchlist_12m[] = {
269{ 15,2,0xFF,0x1B,80,2400,FDC_500KBPS,2,0x54,1,0,FL_MFM }, /* 1.2M */
270{  9,2,0xFF,0x23,40, 720,FDC_300KBPS,2,0x50,1,0,FL_MFM|FL_2STEP }, /* 360K */
271{  9,2,0xFF,0x20,80,1440,FDC_300KBPS,2,0x50,1,0,FL_MFM }, /* 720K */
272};
273
274static struct fd_type fd_searchlist_144m[] = {
275{ 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* 1.44M */
276{  9,2,0xFF,0x20,80,1440,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* 720K */
277};
278
279/* We search for 1.44M first since this is the most common case. */
280static struct fd_type fd_searchlist_288m[] = {
281{ 18,2,0xFF,0x1B,80,2880,FDC_500KBPS,2,0x6C,1,0,FL_MFM }, /* 1.44M */
282#if 0
283{ 36,2,0xFF,0x1B,80,5760,FDC_1MBPS,  2,0x4C,1,1,FL_MFM|FL_PERPND } /* 2.88M */
284#endif
285{  9,2,0xFF,0x20,80,1440,FDC_250KBPS,2,0x50,1,0,FL_MFM }, /* 720K */
286};
287
288#define MAX_SEC_SIZE	(128 << 3)
289#define MAX_CYLINDER	85	/* some people really stress their drives
290				 * up to cyl 82 */
291#define MAX_HEAD	1
292
293static devclass_t fdc_devclass;
294
295/*
296 * Per drive structure (softc).
297 */
298struct fd_data {
299	struct	fdc_data *fdc;	/* pointer to controller structure */
300	int	fdsu;		/* this units number on this controller */
301	enum	fd_drivetype type; /* drive type */
302	struct	fd_type *ft;	/* pointer to current type descriptor */
303	struct	fd_type fts[NUMDENS]; /* type descriptors */
304	int	flags;
305#define	FD_OPEN		0x01	/* it's open		*/
306#define	FD_NONBLOCK	0x02	/* O_NONBLOCK set	*/
307#define	FD_ACTIVE	0x04	/* it's active		*/
308#define	FD_MOTOR	0x08	/* motor should be on	*/
309#define	FD_MOTOR_WAIT	0x10	/* motor coming up	*/
310#define	FD_UA		0x20	/* force unit attention */
311	int	skip;
312	int	hddrv;
313#define FD_NO_TRACK -2
314	int	track;		/* where we think the head is */
315	int	options;	/* user configurable options, see fdcio.h */
316	struct	callout_handle toffhandle;
317	struct	callout_handle tohandle;
318	struct	devstat *device_stats;
319	dev_t	masterdev;
320#ifdef GONE_IN_5
321	eventhandler_tag clonetag;
322	dev_t	clonedevs[NUMDENS - 1];
323#endif
324	device_t dev;
325	fdu_t	fdu;
326};
327
328struct fdc_ivars {
329	int	fdunit;
330};
331static devclass_t fd_devclass;
332
333/* configuration flags for fd */
334#define FD_TYPEMASK	0x0f	/* drive type, matches enum
335				 * fd_drivetype; on i386 machines, if
336				 * given as 0, use RTC type for fd0
337				 * and fd1 */
338#define FD_DTYPE(flags)	((flags) & FD_TYPEMASK)
339#define FD_NO_CHLINE	0x10	/* drive does not support changeline
340				 * aka. unit attention */
341#define FD_NO_PROBE	0x20	/* don't probe drive (seek test), just
342				 * assume it is there */
343
344/*
345 * Throughout this file the following conventions will be used:
346 *
347 * fd is a pointer to the fd_data struct for the drive in question
348 * fdc is a pointer to the fdc_data struct for the controller
349 * fdu is the floppy drive unit number
350 * fdcu is the floppy controller unit number
351 * fdsu is the floppy drive unit number on that controller. (sub-unit)
352 */
353
354/*
355 * Function declarations, same (chaotic) order as they appear in the
356 * file.  Re-ordering is too late now, it would only obfuscate the
357 * diffs against old and offspring versions (like the PC98 one).
358 *
359 * Anyone adding functions here, please keep this sequence the same
360 * as below -- makes locating a particular function in the body much
361 * easier.
362 */
363static void fdout_wr(fdc_p, u_int8_t);
364static u_int8_t fdsts_rd(fdc_p);
365static void fddata_wr(fdc_p, u_int8_t);
366static u_int8_t fddata_rd(fdc_p);
367static void fdctl_wr_isa(fdc_p, u_int8_t);
368#if NCARD > 0
369static void fdctl_wr_pcmcia(fdc_p, u_int8_t);
370#endif
371#if 0
372static u_int8_t fdin_rd(fdc_p);
373#endif
374static int fdc_err(struct fdc_data *, const char *);
375static int fd_cmd(struct fdc_data *, int, ...);
376static int enable_fifo(fdc_p fdc);
377static int fd_sense_drive_status(fdc_p, int *);
378static int fd_sense_int(fdc_p, int *, int *);
379static int fd_read_status(fdc_p);
380static int fdc_alloc_resources(struct fdc_data *);
381static void fdc_release_resources(struct fdc_data *);
382static int fdc_read_ivar(device_t, device_t, int, uintptr_t *);
383static int fdc_probe(device_t);
384#if NCARD > 0
385static int fdc_pccard_probe(device_t);
386#endif
387static int fdc_detach(device_t dev);
388static void fdc_add_child(device_t, const char *, int);
389static int fdc_attach(device_t);
390static int fdc_print_child(device_t, device_t);
391#ifdef GONE_IN_5
392static void fd_clone (void *, char *, int, dev_t *);
393#endif
394static int fd_probe(device_t);
395static int fd_attach(device_t);
396static int fd_detach(device_t);
397static void set_motor(struct fdc_data *, int, int);
398#  define TURNON 1
399#  define TURNOFF 0
400static timeout_t fd_turnoff;
401static timeout_t fd_motor_on;
402static void fd_turnon(struct fd_data *);
403static void fdc_reset(fdc_p);
404static int fd_in(struct fdc_data *, int *);
405static int out_fdc(struct fdc_data *, int);
406/*
407 * The open function is named fdopen() to avoid confusion with fdopen()
408 * in fd(4).  The difference is now only meaningful for debuggers.
409 */
410static	d_open_t	fdopen;
411static	d_close_t	fdclose;
412static	d_strategy_t	fdstrategy;
413static void fdstart(struct fdc_data *);
414static timeout_t fd_iotimeout;
415static timeout_t fd_pseudointr;
416static driver_intr_t fdc_intr;
417static int fdcpio(fdc_p, long, caddr_t, u_int);
418static int fdautoselect(dev_t);
419static int fdstate(struct fdc_data *);
420static int retrier(struct fdc_data *);
421static void fdbiodone(struct bio *);
422static int fdmisccmd(dev_t, u_int, void *);
423static	d_ioctl_t	fdioctl;
424
425static int fifo_threshold = 8;	/* XXX: should be accessible via sysctl */
426
427#ifdef	FDC_DEBUG
428/* CAUTION: fd_debug causes huge amounts of logging output */
429static int volatile fd_debug = 0;
430#define TRACE0(arg) do { if (fd_debug) printf(arg); } while (0)
431#define TRACE1(arg1, arg2) do { if (fd_debug) printf(arg1, arg2); } while (0)
432#else /* FDC_DEBUG */
433#define TRACE0(arg) do { } while (0)
434#define TRACE1(arg1, arg2) do { } while (0)
435#endif /* FDC_DEBUG */
436
437/*
438 * Bus space handling (access to low-level IO).
439 */
440static void
441fdout_wr(fdc_p fdc, u_int8_t v)
442{
443	bus_space_write_1(fdc->portt, fdc->porth, FDOUT+fdc->port_off, v);
444}
445
446static u_int8_t
447fdsts_rd(fdc_p fdc)
448{
449	return bus_space_read_1(fdc->portt, fdc->porth, FDSTS+fdc->port_off);
450}
451
452static void
453fddata_wr(fdc_p fdc, u_int8_t v)
454{
455	bus_space_write_1(fdc->portt, fdc->porth, FDDATA+fdc->port_off, v);
456}
457
458static u_int8_t
459fddata_rd(fdc_p fdc)
460{
461	return bus_space_read_1(fdc->portt, fdc->porth, FDDATA+fdc->port_off);
462}
463
464static void
465fdctl_wr_isa(fdc_p fdc, u_int8_t v)
466{
467	bus_space_write_1(fdc->ctlt, fdc->ctlh, 0, v);
468}
469
470#if NCARD > 0
471static void
472fdctl_wr_pcmcia(fdc_p fdc, u_int8_t v)
473{
474	bus_space_write_1(fdc->portt, fdc->porth, FDCTL+fdc->port_off, v);
475}
476#endif
477
478static u_int8_t
479fdin_rd(fdc_p fdc)
480{
481	return bus_space_read_1(fdc->portt, fdc->porth, FDIN);
482}
483
484#define CDEV_MAJOR 9
485static struct cdevsw fd_cdevsw = {
486	.d_open =	fdopen,
487	.d_close =	fdclose,
488	.d_read =	physread,
489	.d_write =	physwrite,
490	.d_ioctl =	fdioctl,
491	.d_strategy =	fdstrategy,
492	.d_name =	"fd",
493	.d_maj =	CDEV_MAJOR,
494	.d_flags =	D_DISK,
495};
496
497/*
498 * Auxiliary functions.  Well, some only.  Others are scattered
499 * throughout the entire file.
500 */
501static int
502fdc_err(struct fdc_data *fdc, const char *s)
503{
504	fdc->fdc_errs++;
505	if (s) {
506		if (fdc->fdc_errs < FDC_ERRMAX)
507			device_printf(fdc->fdc_dev, "%s", s);
508		else if (fdc->fdc_errs == FDC_ERRMAX)
509			device_printf(fdc->fdc_dev, "too many errors, not "
510						    "logging any more\n");
511	}
512
513	return FD_FAILED;
514}
515
516/*
517 * fd_cmd: Send a command to the chip.  Takes a varargs with this structure:
518 * Unit number,
519 * # of output bytes, output bytes as ints ...,
520 * # of input bytes, input bytes as ints ...
521 */
522static int
523fd_cmd(struct fdc_data *fdc, int n_out, ...)
524{
525	u_char cmd;
526	int n_in;
527	int n;
528	va_list ap;
529
530	va_start(ap, n_out);
531	cmd = (u_char)(va_arg(ap, int));
532	va_end(ap);
533	va_start(ap, n_out);
534	for (n = 0; n < n_out; n++)
535	{
536		if (out_fdc(fdc, va_arg(ap, int)) < 0)
537		{
538			char msg[50];
539			snprintf(msg, sizeof(msg),
540				"cmd %x failed at out byte %d of %d\n",
541				cmd, n + 1, n_out);
542			return fdc_err(fdc, msg);
543		}
544	}
545	n_in = va_arg(ap, int);
546	for (n = 0; n < n_in; n++)
547	{
548		int *ptr = va_arg(ap, int *);
549		if (fd_in(fdc, ptr) < 0)
550		{
551			char msg[50];
552			snprintf(msg, sizeof(msg),
553				"cmd %02x failed at in byte %d of %d\n",
554				cmd, n + 1, n_in);
555			return fdc_err(fdc, msg);
556		}
557	}
558
559	return 0;
560}
561
562static int
563enable_fifo(fdc_p fdc)
564{
565	int i, j;
566
567	if ((fdc->flags & FDC_HAS_FIFO) == 0) {
568
569		/*
570		 * Cannot use fd_cmd the normal way here, since
571		 * this might be an invalid command. Thus we send the
572		 * first byte, and check for an early turn of data directon.
573		 */
574
575		if (out_fdc(fdc, I8207X_CONFIGURE) < 0)
576			return fdc_err(fdc, "Enable FIFO failed\n");
577
578		/* If command is invalid, return */
579		j = FDSTS_TIMEOUT;
580		while ((i = fdsts_rd(fdc) & (NE7_DIO | NE7_RQM))
581		       != NE7_RQM && j-- > 0) {
582			if (i == (NE7_DIO | NE7_RQM)) {
583				fdc_reset(fdc);
584				return FD_FAILED;
585			}
586			DELAY(1);
587		}
588		if (j<0 ||
589		    fd_cmd(fdc, 3,
590			   0, (fifo_threshold - 1) & 0xf, 0, 0) < 0) {
591			fdc_reset(fdc);
592			return fdc_err(fdc, "Enable FIFO failed\n");
593		}
594		fdc->flags |= FDC_HAS_FIFO;
595		return 0;
596	}
597	if (fd_cmd(fdc, 4,
598		   I8207X_CONFIGURE, 0, (fifo_threshold - 1) & 0xf, 0, 0) < 0)
599		return fdc_err(fdc, "Re-enable FIFO failed\n");
600	return 0;
601}
602
603static int
604fd_sense_drive_status(fdc_p fdc, int *st3p)
605{
606	int st3;
607
608	if (fd_cmd(fdc, 2, NE7CMD_SENSED, fdc->fdu, 1, &st3))
609	{
610		return fdc_err(fdc, "Sense Drive Status failed\n");
611	}
612	if (st3p)
613		*st3p = st3;
614
615	return 0;
616}
617
618static int
619fd_sense_int(fdc_p fdc, int *st0p, int *cylp)
620{
621	int cyl, st0, ret;
622
623	ret = fd_cmd(fdc, 1, NE7CMD_SENSEI, 1, &st0);
624	if (ret) {
625		(void)fdc_err(fdc,
626			      "sense intr err reading stat reg 0\n");
627		return ret;
628	}
629
630	if (st0p)
631		*st0p = st0;
632
633	if ((st0 & NE7_ST0_IC) == NE7_ST0_IC_IV) {
634		/*
635		 * There doesn't seem to have been an interrupt.
636		 */
637		return FD_NOT_VALID;
638	}
639
640	if (fd_in(fdc, &cyl) < 0) {
641		return fdc_err(fdc, "can't get cyl num\n");
642	}
643
644	if (cylp)
645		*cylp = cyl;
646
647	return 0;
648}
649
650
651static int
652fd_read_status(fdc_p fdc)
653{
654	int i, ret;
655
656	for (i = ret = 0; i < 7; i++) {
657		/*
658		 * XXX types are poorly chosen.  Only bytes can be read
659		 * from the hardware, but fdc->status[] wants u_ints and
660		 * fd_in() gives ints.
661		 */
662		int status;
663
664		ret = fd_in(fdc, &status);
665		fdc->status[i] = status;
666		if (ret != 0)
667			break;
668	}
669
670	if (ret == 0)
671		fdc->flags |= FDC_STAT_VALID;
672	else
673		fdc->flags &= ~FDC_STAT_VALID;
674
675	return ret;
676}
677
678static int
679fdc_alloc_resources(struct fdc_data *fdc)
680{
681	device_t dev;
682	int ispnp, ispcmcia, nports;
683
684	dev = fdc->fdc_dev;
685	ispnp = (fdc->flags & FDC_ISPNP) != 0;
686	ispcmcia = (fdc->flags & FDC_ISPCMCIA) != 0;
687	fdc->rid_ioport = fdc->rid_irq = fdc->rid_drq = 0;
688	fdc->res_ioport = fdc->res_irq = fdc->res_drq = 0;
689	fdc->rid_ctl = 1;
690
691	/*
692	 * On standard ISA, we don't just use an 8 port range
693	 * (e.g. 0x3f0-0x3f7) since that covers an IDE control
694	 * register at 0x3f6.
695	 *
696	 * Isn't PC hardware wonderful.
697	 *
698	 * The Y-E Data PCMCIA FDC doesn't have this problem, it
699	 * uses the register with offset 6 for pseudo-DMA, and the
700	 * one with offset 7 as control register.
701	 */
702	nports = ispcmcia ? 8 : (ispnp ? 1 : 6);
703
704	/*
705	 * Some ACPI BIOSen have _CRS objects for the floppy device that
706	 * split the I/O port resource into several resources.  We detect
707	 * this case by checking if there are more than 2 IOPORT resources.
708	 * If so, we use the resource with the smallest start address as
709	 * the port RID and the largest start address as the control RID.
710	 */
711	if (bus_get_resource_count(dev, SYS_RES_IOPORT, 2) != 0) {
712		u_long min_start, max_start, tmp;
713		int i;
714
715		/* Find the min/max start addresses and their RIDs. */
716		max_start = 0ul;
717		min_start = ~0ul;
718		for (i = 0; bus_get_resource_count(dev, SYS_RES_IOPORT, i) > 0;
719		    i++) {
720			tmp = bus_get_resource_start(dev, SYS_RES_IOPORT, i);
721			KASSERT(tmp != 0, ("bogus resource"));
722			if (tmp < min_start) {
723				min_start = tmp;
724				fdc->rid_ioport = i;
725			}
726			if (tmp > max_start) {
727				max_start = tmp;
728				fdc->rid_ctl = i;
729			}
730		}
731		if (min_start + 7 != max_start) {
732			device_printf(dev, "I/O to control range incorrect\n");
733			return (ENXIO);
734		}
735	}
736
737	fdc->res_ioport = bus_alloc_resource(dev, SYS_RES_IOPORT,
738					     &fdc->rid_ioport, 0ul, ~0ul,
739					     nports, RF_ACTIVE);
740	if (fdc->res_ioport == 0) {
741		device_printf(dev, "cannot reserve I/O port range (%d ports)\n",
742			      nports);
743		return ENXIO;
744	}
745	fdc->portt = rman_get_bustag(fdc->res_ioport);
746	fdc->porth = rman_get_bushandle(fdc->res_ioport);
747
748	if (!ispcmcia) {
749		/*
750		 * Some BIOSen report the device at 0x3f2-0x3f5,0x3f7
751		 * and some at 0x3f0-0x3f5,0x3f7. We detect the former
752		 * by checking the size and adjust the port address
753		 * accordingly.
754		 */
755		if (bus_get_resource_count(dev, SYS_RES_IOPORT, 0) == 4)
756			fdc->port_off = -2;
757
758		/*
759		 * Register the control port range as rid 1 if it
760		 * isn't there already. Most PnP BIOSen will have
761		 * already done this but non-PnP configurations don't.
762		 *
763		 * And some (!!) report 0x3f2-0x3f5 and completely
764		 * leave out the control register!  It seems that some
765		 * non-antique controller chips have a different
766		 * method of programming the transfer speed which
767		 * doesn't require the control register, but it's
768		 * mighty bogus as the chip still responds to the
769		 * address for the control register.
770		 */
771		if (bus_get_resource_count(dev, SYS_RES_IOPORT, 1) == 0) {
772			u_long ctlstart;
773
774			/* Find the control port, usually 0x3f7 */
775			ctlstart = rman_get_start(fdc->res_ioport) +
776				fdc->port_off + 7;
777
778			bus_set_resource(dev, SYS_RES_IOPORT, 1, ctlstart, 1);
779		}
780
781		/*
782		 * Now (finally!) allocate the control port.
783		 */
784		fdc->res_ctl = bus_alloc_resource(dev, SYS_RES_IOPORT,
785						  &fdc->rid_ctl,
786						  0ul, ~0ul, 1, RF_ACTIVE);
787		if (fdc->res_ctl == 0) {
788			device_printf(dev,
789		"cannot reserve control I/O port range (control port)\n");
790			return ENXIO;
791		}
792		fdc->ctlt = rman_get_bustag(fdc->res_ctl);
793		fdc->ctlh = rman_get_bushandle(fdc->res_ctl);
794	}
795
796	fdc->res_irq = bus_alloc_resource(dev, SYS_RES_IRQ,
797					  &fdc->rid_irq, 0ul, ~0ul, 1,
798					  RF_ACTIVE);
799	if (fdc->res_irq == 0) {
800		device_printf(dev, "cannot reserve interrupt line\n");
801		return ENXIO;
802	}
803
804	if ((fdc->flags & FDC_NODMA) == 0) {
805		fdc->res_drq = bus_alloc_resource(dev, SYS_RES_DRQ,
806						  &fdc->rid_drq, 0ul, ~0ul, 1,
807						  RF_ACTIVE);
808		if (fdc->res_drq == 0) {
809			device_printf(dev, "cannot reserve DMA request line\n");
810			return ENXIO;
811		}
812		fdc->dmachan = fdc->res_drq->r_start;
813	}
814
815	return 0;
816}
817
818static void
819fdc_release_resources(struct fdc_data *fdc)
820{
821	device_t dev;
822
823	dev = fdc->fdc_dev;
824	if (fdc->res_irq != 0) {
825		bus_deactivate_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
826					fdc->res_irq);
827		bus_release_resource(dev, SYS_RES_IRQ, fdc->rid_irq,
828				     fdc->res_irq);
829	}
830	if (fdc->res_ctl != 0) {
831		bus_deactivate_resource(dev, SYS_RES_IOPORT, fdc->rid_ctl,
832					fdc->res_ctl);
833		bus_release_resource(dev, SYS_RES_IOPORT, fdc->rid_ctl,
834				     fdc->res_ctl);
835	}
836	if (fdc->res_ioport != 0) {
837		bus_deactivate_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
838					fdc->res_ioport);
839		bus_release_resource(dev, SYS_RES_IOPORT, fdc->rid_ioport,
840				     fdc->res_ioport);
841	}
842	if (fdc->res_drq != 0) {
843		bus_deactivate_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
844					fdc->res_drq);
845		bus_release_resource(dev, SYS_RES_DRQ, fdc->rid_drq,
846				     fdc->res_drq);
847	}
848}
849
850/*
851 * Configuration/initialization stuff, per controller.
852 */
853
854static struct isa_pnp_id fdc_ids[] = {
855	{0x0007d041, "PC standard floppy disk controller"}, /* PNP0700 */
856	{0x0107d041, "Standard floppy controller supporting MS Device Bay Spec"}, /* PNP0701 */
857	{0}
858};
859
860static int
861fdc_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
862{
863	struct fdc_ivars *ivars = device_get_ivars(child);
864
865	switch (which) {
866	case FDC_IVAR_FDUNIT:
867		*result = ivars->fdunit;
868		break;
869	default:
870		return ENOENT;
871	}
872	return 0;
873}
874
875static int
876fdc_probe(device_t dev)
877{
878	int	error, ic_type;
879	struct	fdc_data *fdc;
880
881	fdc = device_get_softc(dev);
882	bzero(fdc, sizeof *fdc);
883	fdc->fdc_dev = dev;
884	fdc->fdctl_wr = fdctl_wr_isa;
885
886	/* Check pnp ids */
887	error = ISA_PNP_PROBE(device_get_parent(dev), dev, fdc_ids);
888	if (error == ENXIO)
889		return ENXIO;
890	if (error == 0)
891		fdc->flags |= FDC_ISPNP;
892
893	/* Attempt to allocate our resources for the duration of the probe */
894	error = fdc_alloc_resources(fdc);
895	if (error)
896		goto out;
897
898	/* First - lets reset the floppy controller */
899	fdout_wr(fdc, 0);
900	DELAY(100);
901	fdout_wr(fdc, FDO_FRST);
902
903	/* see if it can handle a command */
904	if (fd_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240),
905		   NE7_SPEC_2(2, 0), 0)) {
906		error = ENXIO;
907		goto out;
908	}
909
910	if (fd_cmd(fdc, 1, NE7CMD_VERSION, 1, &ic_type) == 0) {
911		ic_type = (u_char)ic_type;
912		switch (ic_type) {
913		case 0x80:
914			device_set_desc(dev, "NEC 765 or clone");
915			fdc->fdct = FDC_NE765;
916			break;
917		case 0x81:	/* not mentioned in any hardware doc */
918		case 0x90:
919			device_set_desc(dev,
920		"Enhanced floppy controller (i82077, NE72065 or clone)");
921			fdc->fdct = FDC_ENHANCED;
922			break;
923		default:
924			device_set_desc(dev, "Generic floppy controller");
925			fdc->fdct = FDC_UNKNOWN;
926			break;
927		}
928	}
929
930out:
931	fdc_release_resources(fdc);
932	return (error);
933}
934
935#if NCARD > 0
936
937static int
938fdc_pccard_probe(device_t dev)
939{
940	int	error;
941	struct	fdc_data *fdc;
942
943	fdc = device_get_softc(dev);
944	bzero(fdc, sizeof *fdc);
945	fdc->fdc_dev = dev;
946	fdc->fdctl_wr = fdctl_wr_pcmcia;
947
948	fdc->flags |= FDC_ISPCMCIA | FDC_NODMA;
949
950	/* Attempt to allocate our resources for the duration of the probe */
951	error = fdc_alloc_resources(fdc);
952	if (error)
953		goto out;
954
955	/* First - lets reset the floppy controller */
956	fdout_wr(fdc, 0);
957	DELAY(100);
958	fdout_wr(fdc, FDO_FRST);
959
960	/* see if it can handle a command */
961	if (fd_cmd(fdc, 3, NE7CMD_SPECIFY, NE7_SPEC_1(3, 240),
962		   NE7_SPEC_2(2, 0), 0)) {
963		error = ENXIO;
964		goto out;
965	}
966
967	device_set_desc(dev, "Y-E Data PCMCIA floppy");
968	fdc->fdct = FDC_NE765;
969
970out:
971	fdc_release_resources(fdc);
972	return (error);
973}
974
975#endif /* NCARD > 0 */
976
977static int
978fdc_detach(device_t dev)
979{
980	struct	fdc_data *fdc;
981	int	error;
982
983	fdc = device_get_softc(dev);
984
985	/* have our children detached first */
986	if ((error = bus_generic_detach(dev)))
987		return (error);
988
989	/* reset controller, turn motor off */
990	fdout_wr(fdc, 0);
991
992	if ((fdc->flags & FDC_NODMA) == 0)
993		isa_dma_release(fdc->dmachan);
994
995	if ((fdc->flags & FDC_ATTACHED) == 0) {
996		device_printf(dev, "already unloaded\n");
997		return (0);
998	}
999	fdc->flags &= ~FDC_ATTACHED;
1000
1001	BUS_TEARDOWN_INTR(device_get_parent(dev), dev, fdc->res_irq,
1002			  fdc->fdc_intr);
1003	fdc_release_resources(fdc);
1004	device_printf(dev, "unload\n");
1005	return (0);
1006}
1007
1008/*
1009 * Add a child device to the fdc controller.  It will then be probed etc.
1010 */
1011static void
1012fdc_add_child(device_t dev, const char *name, int unit)
1013{
1014	int	flags;
1015	struct fdc_ivars *ivar;
1016	device_t child;
1017
1018	ivar = malloc(sizeof *ivar, M_DEVBUF /* XXX */, M_NOWAIT | M_ZERO);
1019	if (ivar == NULL)
1020		return;
1021	if (resource_int_value(name, unit, "drive", &ivar->fdunit) != 0)
1022		ivar->fdunit = 0;
1023	child = device_add_child(dev, name, unit);
1024	if (child == NULL) {
1025		free(ivar, M_DEVBUF);
1026		return;
1027	}
1028	device_set_ivars(child, ivar);
1029	if (resource_int_value(name, unit, "flags", &flags) == 0)
1030		 device_set_flags(child, flags);
1031	if (resource_disabled(name, unit))
1032		device_disable(child);
1033}
1034
1035static int
1036fdc_attach(device_t dev)
1037{
1038	struct	fdc_data *fdc;
1039	const char *name, *dname;
1040	int	i, error, dunit;
1041
1042	fdc = device_get_softc(dev);
1043	error = fdc_alloc_resources(fdc);
1044	if (error) {
1045		device_printf(dev, "cannot re-acquire resources\n");
1046		return error;
1047	}
1048	error = BUS_SETUP_INTR(device_get_parent(dev), dev, fdc->res_irq,
1049			       INTR_TYPE_BIO | INTR_ENTROPY, fdc_intr, fdc,
1050			       &fdc->fdc_intr);
1051	if (error) {
1052		device_printf(dev, "cannot setup interrupt\n");
1053		return error;
1054	}
1055	fdc->fdcu = device_get_unit(dev);
1056	fdc->flags |= FDC_ATTACHED | FDC_NEEDS_RESET;
1057
1058	if ((fdc->flags & FDC_NODMA) == 0) {
1059		/*
1060		 * Acquire the DMA channel forever, the driver will do
1061		 * the rest
1062		 * XXX should integrate with rman
1063		 */
1064		isa_dma_acquire(fdc->dmachan);
1065		isa_dmainit(fdc->dmachan, MAX_SEC_SIZE);
1066	}
1067	fdc->state = DEVIDLE;
1068
1069	/* reset controller, turn motor off, clear fdout mirror reg */
1070	fdout_wr(fdc, fdc->fdout = 0);
1071	bioq_init(&fdc->head);
1072
1073	/*
1074	 * Probe and attach any children.  We should probably detect
1075	 * devices from the BIOS unless overridden.
1076	 */
1077	name = device_get_nameunit(dev);
1078	i = 0;
1079	while ((resource_find_match(&i, &dname, &dunit, "at", name)) == 0)
1080		fdc_add_child(dev, dname, dunit);
1081
1082	if ((error = bus_generic_attach(dev)) != 0)
1083		return (error);
1084
1085	return (0);
1086}
1087
1088static int
1089fdc_print_child(device_t me, device_t child)
1090{
1091	int retval = 0, flags;
1092
1093	retval += bus_print_child_header(me, child);
1094	retval += printf(" on %s drive %d", device_get_nameunit(me),
1095	       fdc_get_fdunit(child));
1096	if ((flags = device_get_flags(me)) != 0)
1097		retval += printf(" flags %#x", flags);
1098	retval += printf("\n");
1099
1100	return (retval);
1101}
1102
1103static device_method_t fdc_methods[] = {
1104	/* Device interface */
1105	DEVMETHOD(device_probe,		fdc_probe),
1106	DEVMETHOD(device_attach,	fdc_attach),
1107	DEVMETHOD(device_detach,	fdc_detach),
1108	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1109	DEVMETHOD(device_suspend,	bus_generic_suspend),
1110	DEVMETHOD(device_resume,	bus_generic_resume),
1111
1112	/* Bus interface */
1113	DEVMETHOD(bus_print_child,	fdc_print_child),
1114	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
1115	/* Our children never use any other bus interface methods. */
1116
1117	{ 0, 0 }
1118};
1119
1120static driver_t fdc_driver = {
1121	"fdc",
1122	fdc_methods,
1123	sizeof(struct fdc_data)
1124};
1125
1126DRIVER_MODULE(fdc, isa, fdc_driver, fdc_devclass, 0, 0);
1127DRIVER_MODULE(fdc, acpi, fdc_driver, fdc_devclass, 0, 0);
1128
1129#if NCARD > 0
1130
1131static device_method_t fdc_pccard_methods[] = {
1132	/* Device interface */
1133	DEVMETHOD(device_probe,		fdc_pccard_probe),
1134	DEVMETHOD(device_attach,	fdc_attach),
1135	DEVMETHOD(device_detach,	fdc_detach),
1136	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1137	DEVMETHOD(device_suspend,	bus_generic_suspend),
1138	DEVMETHOD(device_resume,	bus_generic_resume),
1139
1140	/* Bus interface */
1141	DEVMETHOD(bus_print_child,	fdc_print_child),
1142	DEVMETHOD(bus_read_ivar,	fdc_read_ivar),
1143	/* Our children never use any other bus interface methods. */
1144
1145	{ 0, 0 }
1146};
1147
1148static driver_t fdc_pccard_driver = {
1149	"fdc",
1150	fdc_pccard_methods,
1151	sizeof(struct fdc_data)
1152};
1153
1154DRIVER_MODULE(fdc, pccard, fdc_pccard_driver, fdc_devclass, 0, 0);
1155
1156#endif /* NCARD > 0 */
1157
1158#ifdef GONE_IN_5
1159/*
1160 * Create a clone device upon request by devfs.
1161 */
1162static void
1163fd_clone(void *arg, char *name, int namelen, dev_t *dev)
1164{
1165	struct	fd_data *fd;
1166	int i, u;
1167	char *n;
1168	size_t l;
1169
1170	fd = (struct fd_data *)arg;
1171	if (*dev != NODEV)
1172		return;
1173	if (dev_stdclone(name, &n, "fd", &u) != 2)
1174		return;
1175	if (u != fd->fdu)
1176		/* unit # mismatch */
1177		return;
1178	l = strlen(n);
1179	if (l == 1 && *n >= 'a' && *n <= 'h') {
1180		/*
1181		 * Trailing letters a through h denote
1182		 * pseudo-partitions.  We don't support true
1183		 * (UFS-style) partitions, so we just implement them
1184		 * as symlinks if someone asks us nicely.
1185		 */
1186		*dev = make_dev_alias(fd->masterdev, name);
1187		return;
1188	}
1189	if (l >= 2 && l <= 5 && *n == '.') {
1190		/*
1191		 * Trailing numbers, preceded by a dot, denote
1192		 * subdevices for different densities.  Historically,
1193		 * they have been named by density (like fd0.1440),
1194		 * but we allow arbitrary numbers between 1 and 4
1195		 * digits, so fd0.1 through fd0.15 are possible as
1196		 * well.
1197		 */
1198		for (i = 1; i < l; i++)
1199			if (n[i] < '0' || n[i] > '9')
1200				return;
1201		for (i = 0; i < NUMDENS - 1; i++)
1202			if (fd->clonedevs[i] == NODEV) {
1203				*dev = make_dev(&fd_cdevsw,
1204						FDNUMTOUNIT(u) + i + 1,
1205						UID_ROOT, GID_OPERATOR, 0640,
1206						name);
1207				fd->clonedevs[i] = *dev;
1208				fd->clonedevs[i]->si_drv1 = fd;
1209				return;
1210			}
1211	}
1212}
1213#endif
1214
1215/*
1216 * Configuration/initialization, per drive.
1217 */
1218static int
1219fd_probe(device_t dev)
1220{
1221	int	i;
1222	u_int	st0, st3;
1223	struct	fd_data *fd;
1224	struct	fdc_data *fdc;
1225	fdsu_t	fdsu;
1226	int	flags;
1227
1228	fdsu = *(int *)device_get_ivars(dev); /* xxx cheat a bit... */
1229	fd = device_get_softc(dev);
1230	fdc = device_get_softc(device_get_parent(dev));
1231	flags = device_get_flags(dev);
1232
1233	bzero(fd, sizeof *fd);
1234	fd->dev = dev;
1235	fd->fdc = fdc;
1236	fd->fdsu = fdsu;
1237	fd->fdu = device_get_unit(dev);
1238	fd->flags = FD_UA;	/* make sure fdautoselect() will be called */
1239
1240	fd->type = FD_DTYPE(flags);
1241/*
1242 * XXX I think using __i386__ is wrong here since we actually want to probe
1243 * for the machine type, not the CPU type (so non-PC arch's like the PC98 will
1244 * fail the probe).  However, for whatever reason, testing for _MACHINE_ARCH
1245 * == i386 breaks the test on FreeBSD/Alpha.
1246 */
1247#if defined(__i386__) || defined(__amd64__)
1248	if (fd->type == FDT_NONE && (fd->fdu == 0 || fd->fdu == 1)) {
1249		/* Look up what the BIOS thinks we have. */
1250		if (fd->fdu == 0) {
1251			if ((fdc->flags & FDC_ISPCMCIA))
1252				/*
1253				 * Somewhat special.  No need to force the
1254				 * user to set device flags, since the Y-E
1255				 * Data PCMCIA floppy is always a 1.44 MB
1256				 * device.
1257				 */
1258				fd->type = FDT_144M;
1259			else
1260				fd->type = (rtcin(RTC_FDISKETTE) & 0xf0) >> 4;
1261		} else {
1262			fd->type = rtcin(RTC_FDISKETTE) & 0x0f;
1263		}
1264		if (fd->type == FDT_288M_1)
1265			fd->type = FDT_288M;
1266	}
1267#endif /* __i386__ || __amd64__ */
1268	/* is there a unit? */
1269	if (fd->type == FDT_NONE)
1270		return (ENXIO);
1271
1272	/* select it */
1273	set_motor(fdc, fdsu, TURNON);
1274	fdc_reset(fdc);		/* XXX reset, then unreset, etc. */
1275	DELAY(1000000);	/* 1 sec */
1276
1277	/* XXX This doesn't work before the first set_motor() */
1278	if ((fdc->flags & FDC_HAS_FIFO) == 0  &&
1279	    fdc->fdct == FDC_ENHANCED &&
1280	    (device_get_flags(fdc->fdc_dev) & FDC_NO_FIFO) == 0 &&
1281	    enable_fifo(fdc) == 0) {
1282		device_printf(device_get_parent(dev),
1283		    "FIFO enabled, %d bytes threshold\n", fifo_threshold);
1284	}
1285
1286	if ((flags & FD_NO_PROBE) == 0) {
1287		/* If we're at track 0 first seek inwards. */
1288		if ((fd_sense_drive_status(fdc, &st3) == 0) &&
1289		    (st3 & NE7_ST3_T0)) {
1290			/* Seek some steps... */
1291			if (fd_cmd(fdc, 3, NE7CMD_SEEK, fdsu, 10, 0) == 0) {
1292				/* ...wait a moment... */
1293				DELAY(300000);
1294				/* make ctrlr happy: */
1295				fd_sense_int(fdc, 0, 0);
1296			}
1297		}
1298
1299		for (i = 0; i < 2; i++) {
1300			/*
1301			 * we must recalibrate twice, just in case the
1302			 * heads have been beyond cylinder 76, since
1303			 * most FDCs still barf when attempting to
1304			 * recalibrate more than 77 steps
1305			 */
1306			/* go back to 0: */
1307			if (fd_cmd(fdc, 2, NE7CMD_RECAL, fdsu, 0) == 0) {
1308				/* a second being enough for full stroke seek*/
1309				DELAY(i == 0 ? 1000000 : 300000);
1310
1311				/* anything responding? */
1312				if (fd_sense_int(fdc, &st0, 0) == 0 &&
1313				    (st0 & NE7_ST0_EC) == 0)
1314					break; /* already probed succesfully */
1315			}
1316		}
1317	}
1318
1319	set_motor(fdc, fdsu, TURNOFF);
1320
1321	if ((flags & FD_NO_PROBE) == 0 &&
1322	    (st0 & NE7_ST0_EC) != 0) /* no track 0 -> no drive present */
1323		return (ENXIO);
1324
1325	switch (fd->type) {
1326	case FDT_12M:
1327		device_set_desc(dev, "1200-KB 5.25\" drive");
1328		fd->type = FDT_12M;
1329		break;
1330	case FDT_144M:
1331		device_set_desc(dev, "1440-KB 3.5\" drive");
1332		fd->type = FDT_144M;
1333		break;
1334	case FDT_288M:
1335		device_set_desc(dev, "2880-KB 3.5\" drive (in 1440-KB mode)");
1336		fd->type = FDT_288M;
1337		break;
1338	case FDT_360K:
1339		device_set_desc(dev, "360-KB 5.25\" drive");
1340		fd->type = FDT_360K;
1341		break;
1342	case FDT_720K:
1343		device_set_desc(dev, "720-KB 3.5\" drive");
1344		fd->type = FDT_720K;
1345		break;
1346	default:
1347		return (ENXIO);
1348	}
1349	fd->track = FD_NO_TRACK;
1350	fd->fdc = fdc;
1351	fd->fdsu = fdsu;
1352	fd->options = 0;
1353	callout_handle_init(&fd->toffhandle);
1354	callout_handle_init(&fd->tohandle);
1355
1356	/* initialize densities for subdevices */
1357	for (i = 0; i < NUMDENS; i++)
1358		memcpy(fd->fts + i, fd_native_types + fd->type,
1359		       sizeof(struct fd_type));
1360	return (0);
1361}
1362
1363static int
1364fd_attach(device_t dev)
1365{
1366	struct	fd_data *fd;
1367
1368	fd = device_get_softc(dev);
1369#ifdef GONE_IN_5
1370	fd->clonetag = EVENTHANDLER_REGISTER(dev_clone, fd_clone, fd, 1000);
1371#endif
1372	fd->masterdev = make_dev(&fd_cdevsw, fd->fdu << 6,
1373				 UID_ROOT, GID_OPERATOR, 0640, "fd%d", fd->fdu);
1374	fd->masterdev->si_drv1 = fd;
1375#ifdef GONE_IN_5
1376	{
1377	int i;
1378	for (i = 0; i < NUMDENS - 1; i++)
1379		fd->clonedevs[i] = NODEV;
1380	}
1381#endif
1382	fd->device_stats = devstat_new_entry(device_get_name(dev),
1383			  device_get_unit(dev), 0, DEVSTAT_NO_ORDERED_TAGS,
1384			  DEVSTAT_TYPE_FLOPPY | DEVSTAT_TYPE_IF_OTHER,
1385			  DEVSTAT_PRIORITY_FD);
1386	return (0);
1387}
1388
1389static int
1390fd_detach(device_t dev)
1391{
1392	struct	fd_data *fd;
1393
1394	fd = device_get_softc(dev);
1395	untimeout(fd_turnoff, fd, fd->toffhandle);
1396	devstat_remove_entry(fd->device_stats);
1397	destroy_dev(fd->masterdev);
1398#ifdef GONE_IN_5
1399	{
1400	int i;
1401	for (i = 0; i < NUMDENS - 1; i++)
1402		if (fd->clonedevs[i] != NODEV)
1403			destroy_dev(fd->clonedevs[i]);
1404	EVENTHANDLER_DEREGISTER(dev_clone, fd->clonetag);
1405	}
1406#endif
1407
1408	return (0);
1409}
1410
1411static device_method_t fd_methods[] = {
1412	/* Device interface */
1413	DEVMETHOD(device_probe,		fd_probe),
1414	DEVMETHOD(device_attach,	fd_attach),
1415	DEVMETHOD(device_detach,	fd_detach),
1416	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
1417	DEVMETHOD(device_suspend,	bus_generic_suspend), /* XXX */
1418	DEVMETHOD(device_resume,	bus_generic_resume), /* XXX */
1419
1420	{ 0, 0 }
1421};
1422
1423static driver_t fd_driver = {
1424	"fd",
1425	fd_methods,
1426	sizeof(struct fd_data)
1427};
1428
1429DRIVER_MODULE(fd, fdc, fd_driver, fd_devclass, 0, 0);
1430
1431/*
1432 * More auxiliary functions.
1433 */
1434/*
1435 * Motor control stuff.
1436 * Remember to not deselect the drive we're working on.
1437 */
1438static void
1439set_motor(struct fdc_data *fdc, int fdsu, int turnon)
1440{
1441	int fdout;
1442
1443	fdout = fdc->fdout;
1444	if (turnon) {
1445		fdout &= ~FDO_FDSEL;
1446		fdout |= (FDO_MOEN0 << fdsu) | FDO_FDMAEN | FDO_FRST | fdsu;
1447	} else
1448		fdout &= ~(FDO_MOEN0 << fdsu);
1449	fdc->fdout = fdout;
1450	fdout_wr(fdc, fdout);
1451	TRACE1("[0x%x->FDOUT]", fdout);
1452}
1453
1454static void
1455fd_turnoff(void *xfd)
1456{
1457	int	s;
1458	fd_p fd = xfd;
1459
1460	TRACE1("[fd%d: turnoff]", fd->fdu);
1461
1462	s = splbio();
1463	/*
1464	 * Don't turn off the motor yet if the drive is active.
1465	 *
1466	 * If we got here, this could only mean we missed an interrupt.
1467	 * This can e. g. happen on the Y-E Date PCMCIA floppy controller
1468	 * after a controller reset.  Just schedule a pseudo-interrupt
1469	 * so the state machine gets re-entered.
1470	 */
1471	if (fd->fdc->state != DEVIDLE && fd->fdc->fdu == fd->fdu) {
1472		fdc_intr(fd->fdc);
1473		splx(s);
1474		return;
1475	}
1476
1477	fd->flags &= ~FD_MOTOR;
1478	set_motor(fd->fdc, fd->fdsu, TURNOFF);
1479	splx(s);
1480}
1481
1482static void
1483fd_motor_on(void *xfd)
1484{
1485	int	s;
1486	fd_p fd = xfd;
1487
1488	s = splbio();
1489	fd->flags &= ~FD_MOTOR_WAIT;
1490	if((fd->fdc->fd == fd) && (fd->fdc->state == MOTORWAIT))
1491	{
1492		fdc_intr(fd->fdc);
1493	}
1494	splx(s);
1495}
1496
1497static void
1498fd_turnon(fd_p fd)
1499{
1500	if(!(fd->flags & FD_MOTOR))
1501	{
1502		fd->flags |= (FD_MOTOR + FD_MOTOR_WAIT);
1503		set_motor(fd->fdc, fd->fdsu, TURNON);
1504		timeout(fd_motor_on, fd, hz); /* in 1 sec its ok */
1505	}
1506}
1507
1508static void
1509fdc_reset(fdc_p fdc)
1510{
1511	/* Try a reset, keep motor on */
1512	fdout_wr(fdc, fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1513	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~(FDO_FRST|FDO_FDMAEN));
1514	DELAY(100);
1515	/* enable FDC, but defer interrupts a moment */
1516	fdout_wr(fdc, fdc->fdout & ~FDO_FDMAEN);
1517	TRACE1("[0x%x->FDOUT]", fdc->fdout & ~FDO_FDMAEN);
1518	DELAY(100);
1519	fdout_wr(fdc, fdc->fdout);
1520	TRACE1("[0x%x->FDOUT]", fdc->fdout);
1521
1522	/* XXX after a reset, silently believe the FDC will accept commands */
1523	(void)fd_cmd(fdc, 3, NE7CMD_SPECIFY,
1524		     NE7_SPEC_1(3, 240), NE7_SPEC_2(2, 0),
1525		     0);
1526	if (fdc->flags & FDC_HAS_FIFO)
1527		(void) enable_fifo(fdc);
1528}
1529
1530/*
1531 * FDC IO functions, take care of the main status register, timeout
1532 * in case the desired status bits are never set.
1533 *
1534 * These PIO loops initially start out with short delays between
1535 * each iteration in the expectation that the required condition
1536 * is usually met quickly, so it can be handled immediately.  After
1537 * about 1 ms, stepping is increased to achieve a better timing
1538 * accuracy in the calls to DELAY().
1539 */
1540static int
1541fd_in(struct fdc_data *fdc, int *ptr)
1542{
1543	int i, j, step;
1544
1545	for (j = 0, step = 1;
1546	    (i = fdsts_rd(fdc) & (NE7_DIO|NE7_RQM)) != (NE7_DIO|NE7_RQM) &&
1547	    j < FDSTS_TIMEOUT;
1548	    j += step) {
1549		if (i == NE7_RQM)
1550			return (fdc_err(fdc, "ready for output in input\n"));
1551		if (j == 1000)
1552			step = 1000;
1553		DELAY(step);
1554	}
1555	if (j >= FDSTS_TIMEOUT)
1556		return (fdc_err(fdc, bootverbose? "input ready timeout\n": 0));
1557#ifdef	FDC_DEBUG
1558	i = fddata_rd(fdc);
1559	TRACE1("[FDDATA->0x%x]", (unsigned char)i);
1560	*ptr = i;
1561	return (0);
1562#else	/* !FDC_DEBUG */
1563	i = fddata_rd(fdc);
1564	if (ptr)
1565		*ptr = i;
1566	return (0);
1567#endif	/* FDC_DEBUG */
1568}
1569
1570static int
1571out_fdc(struct fdc_data *fdc, int x)
1572{
1573	int i, j, step;
1574
1575	for (j = 0, step = 1;
1576	    (i = fdsts_rd(fdc) & (NE7_DIO|NE7_RQM)) != NE7_RQM &&
1577	    j < FDSTS_TIMEOUT;
1578	    j += step) {
1579		if (i == (NE7_DIO|NE7_RQM))
1580			return (fdc_err(fdc, "ready for input in output\n"));
1581		if (j == 1000)
1582			step = 1000;
1583		DELAY(step);
1584	}
1585	if (j >= FDSTS_TIMEOUT)
1586		return (fdc_err(fdc, bootverbose? "output ready timeout\n": 0));
1587
1588	/* Send the command and return */
1589	fddata_wr(fdc, x);
1590	TRACE1("[0x%x->FDDATA]", x);
1591	return (0);
1592}
1593
1594/*
1595 * Block device driver interface functions (interspersed with even more
1596 * auxiliary functions).
1597 */
1598static int
1599fdopen(dev_t dev, int flags, int mode, struct thread *td)
1600{
1601	int type = FDTYPE(minor(dev));
1602	fd_p	fd;
1603	fdc_p	fdc;
1604 	int rv, unitattn, dflags;
1605
1606	fd = dev->si_drv1;
1607	if (fd == NULL)
1608		return (ENXIO);
1609	fdc = fd->fdc;
1610	if ((fdc == NULL) || (fd->type == FDT_NONE))
1611		return (ENXIO);
1612	if (type > NUMDENS)
1613		return (ENXIO);
1614	dflags = device_get_flags(fd->dev);
1615	/*
1616	 * This is a bit bogus.  It's still possible that e. g. a
1617	 * descriptor gets inherited to a child, but then it's at
1618	 * least for the same subdevice.  By checking FD_OPEN here, we
1619	 * can ensure that a device isn't attempted to be opened with
1620	 * different densities at the same time where the second open
1621	 * could clobber the settings from the first one.
1622	 */
1623	if (fd->flags & FD_OPEN)
1624		return (EBUSY);
1625
1626	if (type == 0) {
1627		if (flags & FNONBLOCK) {
1628			/*
1629			 * Unfortunately, physio(9) discards its ioflag
1630			 * argument, thus preventing us from seeing the
1631			 * IO_NDELAY bit.  So we need to keep track
1632			 * ourselves.
1633			 */
1634			fd->flags |= FD_NONBLOCK;
1635			fd->ft = 0;
1636		} else {
1637			/*
1638			 * Figure out a unit attention condition.
1639			 *
1640			 * If UA has been forced, proceed.
1641			 *
1642			 * If the drive has no changeline support,
1643			 * or if the drive parameters have been lost
1644			 * due to previous non-blocking access,
1645			 * assume a forced UA condition.
1646			 *
1647			 * If motor is off, turn it on for a moment
1648			 * and select our drive, in order to read the
1649			 * UA hardware signal.
1650			 *
1651			 * If motor is on, and our drive is currently
1652			 * selected, just read the hardware bit.
1653			 *
1654			 * If motor is on, but active for another
1655			 * drive on that controller, we are lost.  We
1656			 * cannot risk to deselect the other drive, so
1657			 * we just assume a forced UA condition to be
1658			 * on the safe side.
1659			 */
1660			unitattn = 0;
1661			if ((dflags & FD_NO_CHLINE) != 0 ||
1662			    (fd->flags & FD_UA) != 0 ||
1663			    fd->ft == 0) {
1664				unitattn = 1;
1665				fd->flags &= ~FD_UA;
1666			} else if (fdc->fdout & (FDO_MOEN0 | FDO_MOEN1 |
1667						 FDO_MOEN2 | FDO_MOEN3)) {
1668				if ((fdc->fdout & FDO_FDSEL) == fd->fdsu)
1669					unitattn = fdin_rd(fdc) & FDI_DCHG;
1670				else
1671					unitattn = 1;
1672			} else {
1673				set_motor(fdc, fd->fdsu, TURNON);
1674				unitattn = fdin_rd(fdc) & FDI_DCHG;
1675				set_motor(fdc, fd->fdsu, TURNOFF);
1676			}
1677			if (unitattn && (rv = fdautoselect(dev)) != 0)
1678				return (rv);
1679		}
1680	} else {
1681		fd->ft = fd->fts + type;
1682	}
1683	fd->flags |= FD_OPEN;
1684	/*
1685	 * Clearing the DMA overrun counter at open time is a bit messy.
1686	 * Since we're only managing one counter per controller, opening
1687	 * the second drive could mess it up.  Anyway, if the DMA overrun
1688	 * condition is really persistent, it will eventually time out
1689	 * still.  OTOH, clearing it here will ensure we'll at least start
1690	 * trying again after a previous (maybe even long ago) failure.
1691	 * Also, this is merely a stop-gap measure only that should not
1692	 * happen during normal operation, so we can tolerate it to be a
1693	 * bit sloppy about this.
1694	 */
1695	fdc->dma_overruns = 0;
1696
1697	return 0;
1698}
1699
1700static int
1701fdclose(dev_t dev, int flags, int mode, struct thread *td)
1702{
1703	struct fd_data *fd;
1704
1705	fd = dev->si_drv1;
1706	fd->flags &= ~(FD_OPEN | FD_NONBLOCK);
1707	fd->options &= ~(FDOPT_NORETRY | FDOPT_NOERRLOG | FDOPT_NOERROR);
1708
1709	return (0);
1710}
1711
1712static void
1713fdstrategy(struct bio *bp)
1714{
1715	long blknum, nblocks;
1716 	int	s;
1717 	fdu_t	fdu;
1718 	fdc_p	fdc;
1719 	fd_p	fd;
1720	size_t	fdblk;
1721
1722 	fdu = FDUNIT(minor(bp->bio_dev));
1723	fd = bp->bio_dev->si_drv1;
1724	if (fd == NULL)
1725		panic("fdstrategy: buf for nonexistent device (%#lx, %#lx)",
1726		      (u_long)major(bp->bio_dev), (u_long)minor(bp->bio_dev));
1727	fdc = fd->fdc;
1728	bp->bio_resid = bp->bio_bcount;
1729	if (fd->type == FDT_NONE || fd->ft == 0) {
1730		if (fd->type != FDT_NONE && (fd->flags & FD_NONBLOCK))
1731			bp->bio_error = EAGAIN;
1732		else
1733			bp->bio_error = ENXIO;
1734		bp->bio_flags |= BIO_ERROR;
1735		goto bad;
1736	}
1737	fdblk = 128 << (fd->ft->secsize);
1738	if (bp->bio_cmd != FDBIO_FORMAT && bp->bio_cmd != FDBIO_RDSECTID) {
1739		if (fd->flags & FD_NONBLOCK) {
1740			bp->bio_error = EAGAIN;
1741			bp->bio_flags |= BIO_ERROR;
1742			goto bad;
1743		}
1744		if (bp->bio_offset < 0) {
1745			printf(
1746		"fd%d: fdstrat: bad request offset = %ju, bcount = %ld\n",
1747			       fdu, (intmax_t)bp->bio_offset, bp->bio_bcount);
1748			bp->bio_error = EINVAL;
1749			bp->bio_flags |= BIO_ERROR;
1750			goto bad;
1751		}
1752		if ((bp->bio_bcount % fdblk) != 0) {
1753			bp->bio_error = EINVAL;
1754			bp->bio_flags |= BIO_ERROR;
1755			goto bad;
1756		}
1757	}
1758
1759	/*
1760	 * Set up block calculations.
1761	 */
1762	if (bp->bio_offset >= ((off_t)128 << fd->ft->secsize) * fd->ft->size) {
1763		bp->bio_error = EINVAL;
1764		bp->bio_flags |= BIO_ERROR;
1765		goto bad;
1766	}
1767	blknum = bp->bio_offset / fdblk;
1768 	nblocks = fd->ft->size;
1769	if (blknum + bp->bio_bcount / fdblk > nblocks) {
1770		if (blknum >= nblocks) {
1771			if (bp->bio_cmd != BIO_READ) {
1772				bp->bio_error = ENOSPC;
1773				bp->bio_flags |= BIO_ERROR;
1774			}
1775			goto bad;	/* not always bad, but EOF */
1776		}
1777		bp->bio_bcount = (nblocks - blknum) * fdblk;
1778	}
1779 	bp->bio_pblkno = blknum;
1780	s = splbio();
1781	bioq_disksort(&fdc->head, bp);
1782	untimeout(fd_turnoff, fd, fd->toffhandle); /* a good idea */
1783	devstat_start_transaction_bio(fd->device_stats, bp);
1784	device_busy(fd->dev);
1785	fdstart(fdc);
1786	splx(s);
1787	return;
1788
1789bad:
1790	biodone(bp);
1791}
1792
1793/*
1794 * fdstart
1795 *
1796 * We have just queued something.  If the controller is not busy
1797 * then simulate the case where it has just finished a command
1798 * So that it (the interrupt routine) looks on the queue for more
1799 * work to do and picks up what we just added.
1800 *
1801 * If the controller is already busy, we need do nothing, as it
1802 * will pick up our work when the present work completes.
1803 */
1804static void
1805fdstart(struct fdc_data *fdc)
1806{
1807	int s;
1808
1809	s = splbio();
1810	if(fdc->state == DEVIDLE)
1811	{
1812		fdc_intr(fdc);
1813	}
1814	splx(s);
1815}
1816
1817static void
1818fd_iotimeout(void *xfdc)
1819{
1820 	fdc_p fdc;
1821	int s;
1822
1823	fdc = xfdc;
1824	TRACE1("fd%d[fd_iotimeout()]", fdc->fdu);
1825
1826	/*
1827	 * Due to IBM's brain-dead design, the FDC has a faked ready
1828	 * signal, hardwired to ready == true. Thus, any command
1829	 * issued if there's no diskette in the drive will _never_
1830	 * complete, and must be aborted by resetting the FDC.
1831	 * Many thanks, Big Blue!
1832	 * The FDC must not be reset directly, since that would
1833	 * interfere with the state machine.  Instead, pretend that
1834	 * the command completed but was invalid.  The state machine
1835	 * will reset the FDC and retry once.
1836	 */
1837	s = splbio();
1838	fdc->status[0] = NE7_ST0_IC_IV;
1839	fdc->flags &= ~FDC_STAT_VALID;
1840	fdc->state = IOTIMEDOUT;
1841	fdc_intr(fdc);
1842	splx(s);
1843}
1844
1845/* Just ensure it has the right spl. */
1846static void
1847fd_pseudointr(void *xfdc)
1848{
1849	int	s;
1850
1851	s = splbio();
1852	fdc_intr(xfdc);
1853	splx(s);
1854}
1855
1856/*
1857 * fdc_intr
1858 *
1859 * Keep calling the state machine until it returns a 0.
1860 * Always called at splbio.
1861 */
1862static void
1863fdc_intr(void *xfdc)
1864{
1865	fdc_p fdc = xfdc;
1866	while(fdstate(fdc))
1867		;
1868}
1869
1870/*
1871 * Magic pseudo-DMA initialization for YE FDC. Sets count and
1872 * direction.
1873 */
1874#define SET_BCDR(fdc,wr,cnt,port) \
1875	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port,	 \
1876	    ((cnt)-1) & 0xff);						 \
1877	bus_space_write_1(fdc->portt, fdc->porth, fdc->port_off + port + 1, \
1878	    ((wr ? 0x80 : 0) | ((((cnt)-1) >> 8) & 0x7f)));
1879
1880/*
1881 * fdcpio(): perform programmed IO read/write for YE PCMCIA floppy.
1882 */
1883static int
1884fdcpio(fdc_p fdc, long flags, caddr_t addr, u_int count)
1885{
1886	u_char *cptr = (u_char *)addr;
1887
1888	if (flags == BIO_READ) {
1889		if (fdc->state != PIOREAD) {
1890			fdc->state = PIOREAD;
1891			return(0);
1892		}
1893		SET_BCDR(fdc, 0, count, 0);
1894		bus_space_read_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1895		    FDC_YE_DATAPORT, cptr, count);
1896	} else {
1897		bus_space_write_multi_1(fdc->portt, fdc->porth, fdc->port_off +
1898		    FDC_YE_DATAPORT, cptr, count);
1899		SET_BCDR(fdc, 0, count, 0);
1900	}
1901	return(1);
1902}
1903
1904/*
1905 * Try figuring out the density of the media present in our device.
1906 */
1907static int
1908fdautoselect(dev_t dev)
1909{
1910	fdu_t fdu;
1911 	fd_p fd;
1912	struct fd_type *fdtp;
1913	struct fdc_readid id;
1914	int i, n, oopts, rv;
1915
1916 	fdu = FDUNIT(minor(dev));
1917	fd = dev->si_drv1;
1918
1919	switch (fd->type) {
1920	default:
1921		return (ENXIO);
1922
1923	case FDT_360K:
1924	case FDT_720K:
1925		/* no autoselection on those drives */
1926		fd->ft = fd_native_types + fd->type;
1927		return (0);
1928
1929	case FDT_12M:
1930		fdtp = fd_searchlist_12m;
1931		n = sizeof fd_searchlist_12m / sizeof(struct fd_type);
1932		break;
1933
1934	case FDT_144M:
1935		fdtp = fd_searchlist_144m;
1936		n = sizeof fd_searchlist_144m / sizeof(struct fd_type);
1937		break;
1938
1939	case FDT_288M:
1940		fdtp = fd_searchlist_288m;
1941		n = sizeof fd_searchlist_288m / sizeof(struct fd_type);
1942		break;
1943	}
1944
1945	/*
1946	 * Try reading sector ID fields, first at cylinder 0, head 0,
1947	 * then at cylinder 2, head N.  We don't probe cylinder 1,
1948	 * since for 5.25in DD media in a HD drive, there are no data
1949	 * to read (2 step pulses per media cylinder required).  For
1950	 * two-sided media, the second probe always goes to head 1, so
1951	 * we can tell them apart from single-sided media.  As a
1952	 * side-effect this means that single-sided media should be
1953	 * mentioned in the search list after two-sided media of an
1954	 * otherwise identical density.  Media with a different number
1955	 * of sectors per track but otherwise identical parameters
1956	 * cannot be distinguished at all.
1957	 *
1958	 * If we successfully read an ID field on both cylinders where
1959	 * the recorded values match our expectation, we are done.
1960	 * Otherwise, we try the next density entry from the table.
1961	 *
1962	 * Stepping to cylinder 2 has the side-effect of clearing the
1963	 * unit attention bit.
1964	 */
1965	oopts = fd->options;
1966	fd->options |= FDOPT_NOERRLOG | FDOPT_NORETRY;
1967	for (i = 0; i < n; i++, fdtp++) {
1968		fd->ft = fdtp;
1969
1970		id.cyl = id.head = 0;
1971		rv = fdmisccmd(dev, FDBIO_RDSECTID, &id);
1972		if (rv != 0)
1973			continue;
1974		if (id.cyl != 0 || id.head != 0 ||
1975		    id.secshift != fdtp->secsize)
1976			continue;
1977		id.cyl = 2;
1978		id.head = fd->ft->heads - 1;
1979		rv = fdmisccmd(dev, FDBIO_RDSECTID, &id);
1980		if (id.cyl != 2 || id.head != fdtp->heads - 1 ||
1981		    id.secshift != fdtp->secsize)
1982			continue;
1983		if (rv == 0)
1984			break;
1985	}
1986
1987	fd->options = oopts;
1988	if (i == n) {
1989		if (bootverbose)
1990			device_printf(fd->dev, "autoselection failed\n");
1991		fd->ft = 0;
1992		return (EIO);
1993	} else {
1994		if (bootverbose)
1995			device_printf(fd->dev, "autoselected %d KB medium\n",
1996				      fd->ft->size / 2);
1997		return (0);
1998	}
1999}
2000
2001
2002/*
2003 * The controller state machine.
2004 *
2005 * If it returns a non zero value, it should be called again immediately.
2006 */
2007static int
2008fdstate(fdc_p fdc)
2009{
2010	struct fdc_readid *idp;
2011	int read, format, rdsectid, cylinder, head, i, sec = 0, sectrac;
2012	int st0, cyl, st3, idf, ne7cmd, mfm, steptrac;
2013	unsigned long blknum;
2014	fdu_t fdu = fdc->fdu;
2015	fd_p fd;
2016	register struct bio *bp;
2017	struct fd_formb *finfo = NULL;
2018	size_t fdblk;
2019
2020	bp = fdc->bp;
2021	if (bp == NULL) {
2022		bp = bioq_first(&fdc->head);
2023		if (bp != NULL) {
2024			bioq_remove(&fdc->head, bp);
2025			fdc->bp = bp;
2026		}
2027	}
2028	if (bp == NULL) {
2029		/*
2030		 * Nothing left for this controller to do,
2031		 * force into the IDLE state.
2032		 */
2033		fdc->state = DEVIDLE;
2034		if (fdc->fd) {
2035			device_printf(fdc->fdc_dev,
2036			    "unexpected valid fd pointer\n");
2037			fdc->fd = (fd_p) 0;
2038			fdc->fdu = -1;
2039		}
2040		TRACE1("[fdc%d IDLE]", fdc->fdcu);
2041 		return (0);
2042	}
2043	fdu = FDUNIT(minor(bp->bio_dev));
2044	fd = bp->bio_dev->si_drv1;
2045	fdblk = 128 << fd->ft->secsize;
2046	if (fdc->fd && (fd != fdc->fd))
2047		device_printf(fd->dev, "confused fd pointers\n");
2048	read = bp->bio_cmd == BIO_READ;
2049	mfm = (fd->ft->flags & FL_MFM)? NE7CMD_MFM: 0;
2050	steptrac = (fd->ft->flags & FL_2STEP)? 2: 1;
2051	if (read)
2052		idf = ISADMA_READ;
2053	else
2054		idf = ISADMA_WRITE;
2055	format = bp->bio_cmd == FDBIO_FORMAT;
2056	rdsectid = bp->bio_cmd == FDBIO_RDSECTID;
2057	if (format)
2058		finfo = (struct fd_formb *)bp->bio_data;
2059	TRACE1("fd%d", fdu);
2060	TRACE1("[%s]", fdstates[fdc->state]);
2061	TRACE1("(0x%x)", fd->flags);
2062	untimeout(fd_turnoff, fd, fd->toffhandle);
2063	fd->toffhandle = timeout(fd_turnoff, fd, 4 * hz);
2064	switch (fdc->state)
2065	{
2066	case DEVIDLE:
2067	case FINDWORK:	/* we have found new work */
2068		fdc->retry = 0;
2069		fd->skip = 0;
2070		fdc->fd = fd;
2071		fdc->fdu = fdu;
2072		fdc->fdctl_wr(fdc, fd->ft->trans);
2073		TRACE1("[0x%x->FDCTL]", fd->ft->trans);
2074		/*
2075		 * If the next drive has a motor startup pending, then
2076		 * it will start up in its own good time.
2077		 */
2078		if(fd->flags & FD_MOTOR_WAIT) {
2079			fdc->state = MOTORWAIT;
2080			return (0); /* will return later */
2081		}
2082		/*
2083		 * Maybe if it's not starting, it SHOULD be starting.
2084		 */
2085		if (!(fd->flags & FD_MOTOR))
2086		{
2087			fdc->state = MOTORWAIT;
2088			fd_turnon(fd);
2089			return (0); /* will return later */
2090		}
2091		else	/* at least make sure we are selected */
2092		{
2093			set_motor(fdc, fd->fdsu, TURNON);
2094		}
2095		if (fdc->flags & FDC_NEEDS_RESET) {
2096			fdc->state = RESETCTLR;
2097			fdc->flags &= ~FDC_NEEDS_RESET;
2098		} else
2099			fdc->state = DOSEEK;
2100		return (1);	/* will return immediately */
2101
2102	case DOSEEK:
2103		blknum = bp->bio_pblkno + fd->skip / fdblk;
2104		cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
2105		if (cylinder == fd->track)
2106		{
2107			fdc->state = SEEKCOMPLETE;
2108			return (1); /* will return immediately */
2109		}
2110		if (fd_cmd(fdc, 3, NE7CMD_SEEK,
2111			   fd->fdsu, cylinder * steptrac, 0))
2112		{
2113			/*
2114			 * Seek command not accepted, looks like
2115			 * the FDC went off to the Saints...
2116			 */
2117			fdc->retry = 6;	/* try a reset */
2118			return(retrier(fdc));
2119		}
2120		fd->track = FD_NO_TRACK;
2121		fdc->state = SEEKWAIT;
2122		return(0);	/* will return later */
2123
2124	case SEEKWAIT:
2125		/* allow heads to settle */
2126		timeout(fd_pseudointr, fdc, hz / 16);
2127		fdc->state = SEEKCOMPLETE;
2128		return(0);	/* will return later */
2129
2130	case SEEKCOMPLETE : /* seek done, start DMA */
2131		blknum = bp->bio_pblkno + fd->skip / fdblk;
2132		cylinder = blknum / (fd->ft->sectrac * fd->ft->heads);
2133
2134		/* Make sure seek really happened. */
2135		if(fd->track == FD_NO_TRACK) {
2136			int descyl = cylinder * steptrac;
2137			do {
2138				/*
2139				 * This might be a "ready changed" interrupt,
2140				 * which cannot really happen since the
2141				 * RDY pin is hardwired to + 5 volts.  This
2142				 * generally indicates a "bouncing" intr
2143				 * line, so do one of the following:
2144				 *
2145				 * When running on an enhanced FDC that is
2146				 * known to not go stuck after responding
2147				 * with INVALID, fetch all interrupt states
2148				 * until seeing either an INVALID or a
2149				 * real interrupt condition.
2150				 *
2151				 * When running on a dumb old NE765, give
2152				 * up immediately.  The controller will
2153				 * provide up to four dummy RC interrupt
2154				 * conditions right after reset (for the
2155				 * corresponding four drives), so this is
2156				 * our only chance to get notice that it
2157				 * was not the FDC that caused the interrupt.
2158				 */
2159				if (fd_sense_int(fdc, &st0, &cyl)
2160				    == FD_NOT_VALID)
2161					return (0); /* will return later */
2162				if(fdc->fdct == FDC_NE765
2163				   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
2164					return (0); /* hope for a real intr */
2165			} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
2166
2167			if (0 == descyl) {
2168				int failed = 0;
2169				/*
2170				 * seek to cyl 0 requested; make sure we are
2171				 * really there
2172				 */
2173				if (fd_sense_drive_status(fdc, &st3))
2174					failed = 1;
2175				if ((st3 & NE7_ST3_T0) == 0) {
2176					printf(
2177		"fd%d: Seek to cyl 0, but not really there (ST3 = %b)\n",
2178					       fdu, st3, NE7_ST3BITS);
2179					failed = 1;
2180				}
2181
2182				if (failed) {
2183					if(fdc->retry < 3)
2184						fdc->retry = 3;
2185					return (retrier(fdc));
2186				}
2187			}
2188
2189			if (cyl != descyl) {
2190				printf(
2191		"fd%d: Seek to cyl %d failed; am at cyl %d (ST0 = 0x%x)\n",
2192				       fdu, descyl, cyl, st0);
2193				if (fdc->retry < 3)
2194					fdc->retry = 3;
2195				return (retrier(fdc));
2196			}
2197		}
2198
2199		fd->track = cylinder;
2200		if (format)
2201			fd->skip = (char *)&(finfo->fd_formb_cylno(0))
2202			    - (char *)finfo;
2203		if (!rdsectid && !(fdc->flags & FDC_NODMA))
2204			isa_dmastart(idf, bp->bio_data+fd->skip,
2205				format ? bp->bio_bcount : fdblk, fdc->dmachan);
2206		blknum = bp->bio_pblkno + fd->skip / fdblk;
2207		sectrac = fd->ft->sectrac;
2208		sec = blknum %  (sectrac * fd->ft->heads);
2209		head = sec / sectrac;
2210		sec = sec % sectrac + 1;
2211		if (head != 0 && fd->ft->offset_side2 != 0)
2212			sec += fd->ft->offset_side2;
2213		fd->hddrv = ((head&1)<<2)+fdu;
2214
2215		if(format || !(read || rdsectid))
2216		{
2217			/* make sure the drive is writable */
2218			if(fd_sense_drive_status(fdc, &st3) != 0)
2219			{
2220				/* stuck controller? */
2221				if (!(fdc->flags & FDC_NODMA))
2222					isa_dmadone(idf,
2223						    bp->bio_data + fd->skip,
2224						    format ? bp->bio_bcount : fdblk,
2225						    fdc->dmachan);
2226				fdc->retry = 6;	/* reset the beast */
2227				return (retrier(fdc));
2228			}
2229			if(st3 & NE7_ST3_WP)
2230			{
2231				/*
2232				 * XXX YES! this is ugly.
2233				 * in order to force the current operation
2234				 * to fail, we will have to fake an FDC
2235				 * error - all error handling is done
2236				 * by the retrier()
2237				 */
2238				fdc->status[0] = NE7_ST0_IC_AT;
2239				fdc->status[1] = NE7_ST1_NW;
2240				fdc->status[2] = 0;
2241				fdc->status[3] = fd->track;
2242				fdc->status[4] = head;
2243				fdc->status[5] = sec;
2244				fdc->retry = 8;	/* break out immediately */
2245				fdc->state = IOTIMEDOUT; /* not really... */
2246				return (1); /* will return immediately */
2247			}
2248		}
2249
2250		if (format) {
2251			ne7cmd = NE7CMD_FORMAT | mfm;
2252			if (fdc->flags & FDC_NODMA) {
2253				/*
2254				 * This seems to be necessary for
2255				 * whatever obscure reason; if we omit
2256				 * it, we end up filling the sector ID
2257				 * fields of the newly formatted track
2258				 * entirely with garbage, causing
2259				 * `wrong cylinder' errors all over
2260				 * the place when trying to read them
2261				 * back.
2262				 *
2263				 * Umpf.
2264				 */
2265				SET_BCDR(fdc, 1, bp->bio_bcount, 0);
2266
2267				(void)fdcpio(fdc,bp->bio_cmd,
2268					bp->bio_data+fd->skip,
2269					bp->bio_bcount);
2270
2271			}
2272			/* formatting */
2273			if(fd_cmd(fdc, 6,  ne7cmd, head << 2 | fdu,
2274				  finfo->fd_formb_secshift,
2275				  finfo->fd_formb_nsecs,
2276				  finfo->fd_formb_gaplen,
2277				  finfo->fd_formb_fillbyte, 0)) {
2278				/* controller fell over */
2279				if (!(fdc->flags & FDC_NODMA))
2280					isa_dmadone(idf,
2281						    bp->bio_data + fd->skip,
2282						    format ? bp->bio_bcount : fdblk,
2283						    fdc->dmachan);
2284				fdc->retry = 6;
2285				return (retrier(fdc));
2286			}
2287		} else if (rdsectid) {
2288			ne7cmd = NE7CMD_READID | mfm;
2289			if (fd_cmd(fdc, 2, ne7cmd, head << 2 | fdu, 0)) {
2290				/* controller jamming */
2291				fdc->retry = 6;
2292				return (retrier(fdc));
2293			}
2294		} else {
2295			/* read or write operation */
2296			ne7cmd = (read ? NE7CMD_READ | NE7CMD_SK : NE7CMD_WRITE) | mfm;
2297			if (fdc->flags & FDC_NODMA) {
2298				/*
2299				 * This seems to be necessary even when
2300				 * reading data.
2301				 */
2302				SET_BCDR(fdc, 1, fdblk, 0);
2303
2304				/*
2305				 * Perform the write pseudo-DMA before
2306				 * the WRITE command is sent.
2307				 */
2308				if (!read)
2309					(void)fdcpio(fdc,bp->bio_cmd,
2310					    bp->bio_data+fd->skip,
2311					    fdblk);
2312			}
2313			if (fd_cmd(fdc, 9,
2314				   ne7cmd,
2315				   head << 2 | fdu,  /* head & unit */
2316				   fd->track,        /* track */
2317				   head,
2318				   sec,              /* sector + 1 */
2319				   fd->ft->secsize,  /* sector size */
2320				   sectrac,          /* sectors/track */
2321				   fd->ft->gap,      /* gap size */
2322				   fd->ft->datalen,  /* data length */
2323				   0)) {
2324				/* the beast is sleeping again */
2325				if (!(fdc->flags & FDC_NODMA))
2326					isa_dmadone(idf,
2327						    bp->bio_data + fd->skip,
2328						    format ? bp->bio_bcount : fdblk,
2329						    fdc->dmachan);
2330				fdc->retry = 6;
2331				return (retrier(fdc));
2332			}
2333		}
2334		if (!rdsectid && (fdc->flags & FDC_NODMA))
2335			/*
2336			 * If this is a read, then simply await interrupt
2337			 * before performing PIO.
2338			 */
2339			if (read && !fdcpio(fdc,bp->bio_cmd,
2340			    bp->bio_data+fd->skip,fdblk)) {
2341				fd->tohandle = timeout(fd_iotimeout, fdc, hz);
2342				return(0);      /* will return later */
2343			}
2344
2345		/*
2346		 * Write (or format) operation will fall through and
2347		 * await completion interrupt.
2348		 */
2349		fdc->state = IOCOMPLETE;
2350		fd->tohandle = timeout(fd_iotimeout, fdc, hz);
2351		return (0);	/* will return later */
2352
2353	case PIOREAD:
2354		/*
2355		 * Actually perform the PIO read.  The IOCOMPLETE case
2356		 * removes the timeout for us.
2357		 */
2358		(void)fdcpio(fdc,bp->bio_cmd,bp->bio_data+fd->skip,fdblk);
2359		fdc->state = IOCOMPLETE;
2360		/* FALLTHROUGH */
2361	case IOCOMPLETE: /* IO done, post-analyze */
2362		untimeout(fd_iotimeout, fdc, fd->tohandle);
2363
2364		if (fd_read_status(fdc)) {
2365			if (!rdsectid && !(fdc->flags & FDC_NODMA))
2366				isa_dmadone(idf, bp->bio_data + fd->skip,
2367					    format ? bp->bio_bcount : fdblk,
2368					    fdc->dmachan);
2369			if (fdc->retry < 6)
2370				fdc->retry = 6;	/* force a reset */
2371			return (retrier(fdc));
2372  		}
2373
2374		fdc->state = IOTIMEDOUT;
2375
2376		/* FALLTHROUGH */
2377	case IOTIMEDOUT:
2378		if (!rdsectid && !(fdc->flags & FDC_NODMA))
2379			isa_dmadone(idf, bp->bio_data + fd->skip,
2380				format ? bp->bio_bcount : fdblk, fdc->dmachan);
2381		if (fdc->status[0] & NE7_ST0_IC) {
2382                        if ((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2383			    && fdc->status[1] & NE7_ST1_OR) {
2384                                /*
2385				 * DMA overrun. Someone hogged the bus and
2386				 * didn't release it in time for the next
2387				 * FDC transfer.
2388				 *
2389				 * We normally restart this without bumping
2390				 * the retry counter.  However, in case
2391				 * something is seriously messed up (like
2392				 * broken hardware), we rather limit the
2393				 * number of retries so the IO operation
2394				 * doesn't block indefinately.
2395				 */
2396				if (fdc->dma_overruns++ < FDC_DMAOV_MAX) {
2397					fdc->state = SEEKCOMPLETE;
2398					return (1);/* will return immediately */
2399				} /* else fall through */
2400                        }
2401			if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_IV
2402				&& fdc->retry < 6)
2403				fdc->retry = 6;	/* force a reset */
2404			else if((fdc->status[0] & NE7_ST0_IC) == NE7_ST0_IC_AT
2405				&& fdc->status[2] & NE7_ST2_WC
2406				&& fdc->retry < 3)
2407				fdc->retry = 3;	/* force recalibrate */
2408			return (retrier(fdc));
2409		}
2410		/* All OK */
2411		if (rdsectid) {
2412			/* copy out ID field contents */
2413			idp = (struct fdc_readid *)bp->bio_data;
2414			idp->cyl = fdc->status[3];
2415			idp->head = fdc->status[4];
2416			idp->sec = fdc->status[5];
2417			idp->secshift = fdc->status[6];
2418		}
2419		/* Operation successful, retry DMA overruns again next time. */
2420		fdc->dma_overruns = 0;
2421		fd->skip += fdblk;
2422		if (!rdsectid && !format && fd->skip < bp->bio_bcount) {
2423			/* set up next transfer */
2424			fdc->state = DOSEEK;
2425		} else {
2426			/* ALL DONE */
2427			fd->skip = 0;
2428			bp->bio_resid = 0;
2429			fdc->bp = NULL;
2430			device_unbusy(fd->dev);
2431			biofinish(bp, fd->device_stats, 0);
2432			fdc->fd = (fd_p) 0;
2433			fdc->fdu = -1;
2434			fdc->state = FINDWORK;
2435		}
2436		return (1);	/* will return immediately */
2437
2438	case RESETCTLR:
2439		fdc_reset(fdc);
2440		fdc->retry++;
2441		fdc->state = RESETCOMPLETE;
2442		return (0);	/* will return later */
2443
2444	case RESETCOMPLETE:
2445		/*
2446		 * Discard all the results from the reset so that they
2447		 * can't cause an unexpected interrupt later.
2448		 */
2449		for (i = 0; i < 4; i++)
2450			(void)fd_sense_int(fdc, &st0, &cyl);
2451		fdc->state = STARTRECAL;
2452		/* FALLTHROUGH */
2453	case STARTRECAL:
2454		if(fd_cmd(fdc, 2, NE7CMD_RECAL, fdu, 0)) {
2455			/* arrgl */
2456			fdc->retry = 6;
2457			return (retrier(fdc));
2458		}
2459		fdc->state = RECALWAIT;
2460		return (0);	/* will return later */
2461
2462	case RECALWAIT:
2463		/* allow heads to settle */
2464		timeout(fd_pseudointr, fdc, hz / 8);
2465		fdc->state = RECALCOMPLETE;
2466		return (0);	/* will return later */
2467
2468	case RECALCOMPLETE:
2469		do {
2470			/*
2471			 * See SEEKCOMPLETE for a comment on this:
2472			 */
2473			if (fd_sense_int(fdc, &st0, &cyl) == FD_NOT_VALID)
2474				return (0); /* will return later */
2475			if(fdc->fdct == FDC_NE765
2476			   && (st0 & NE7_ST0_IC) == NE7_ST0_IC_RC)
2477				return (0); /* hope for a real intr */
2478		} while ((st0 & NE7_ST0_IC) == NE7_ST0_IC_RC);
2479		if ((st0 & NE7_ST0_IC) != NE7_ST0_IC_NT || cyl != 0)
2480		{
2481			if(fdc->retry > 3)
2482				/*
2483				 * A recalibrate from beyond cylinder 77
2484				 * will "fail" due to the FDC limitations;
2485				 * since people used to complain much about
2486				 * the failure message, try not logging
2487				 * this one if it seems to be the first
2488				 * time in a line.
2489				 */
2490				printf("fd%d: recal failed ST0 %b cyl %d\n",
2491				       fdu, st0, NE7_ST0BITS, cyl);
2492			if(fdc->retry < 3) fdc->retry = 3;
2493			return (retrier(fdc));
2494		}
2495		fd->track = 0;
2496		/* Seek (probably) necessary */
2497		fdc->state = DOSEEK;
2498		return (1);	/* will return immediately */
2499
2500	case MOTORWAIT:
2501		if(fd->flags & FD_MOTOR_WAIT)
2502		{
2503			return (0); /* time's not up yet */
2504		}
2505		if (fdc->flags & FDC_NEEDS_RESET) {
2506			fdc->state = RESETCTLR;
2507			fdc->flags &= ~FDC_NEEDS_RESET;
2508		} else
2509			fdc->state = DOSEEK;
2510		return (1);	/* will return immediately */
2511
2512	default:
2513		device_printf(fdc->fdc_dev, "unexpected FD int->");
2514		if (fd_read_status(fdc) == 0)
2515			printf("FDC status :%x %x %x %x %x %x %x   ",
2516			       fdc->status[0],
2517			       fdc->status[1],
2518			       fdc->status[2],
2519			       fdc->status[3],
2520			       fdc->status[4],
2521			       fdc->status[5],
2522			       fdc->status[6] );
2523		else
2524			printf("No status available   ");
2525		if (fd_sense_int(fdc, &st0, &cyl) != 0)
2526		{
2527			printf("[controller is dead now]\n");
2528			return (0); /* will return later */
2529		}
2530		printf("ST0 = %x, PCN = %x\n", st0, cyl);
2531		return (0);	/* will return later */
2532	}
2533	/* noone should ever get here */
2534}
2535
2536static int
2537retrier(struct fdc_data *fdc)
2538{
2539	struct bio *bp;
2540	struct fd_data *fd;
2541	int fdu;
2542
2543	bp = fdc->bp;
2544
2545	/* XXX shouldn't this be cached somewhere?  */
2546	fdu = FDUNIT(minor(bp->bio_dev));
2547	fd = bp->bio_dev->si_drv1;
2548	if (fd->options & FDOPT_NORETRY)
2549		goto fail;
2550
2551	switch (fdc->retry) {
2552	case 0: case 1: case 2:
2553		fdc->state = SEEKCOMPLETE;
2554		break;
2555	case 3: case 4: case 5:
2556		fdc->state = STARTRECAL;
2557		break;
2558	case 6:
2559		fdc->state = RESETCTLR;
2560		break;
2561	case 7:
2562		break;
2563	default:
2564	fail:
2565		if ((fd->options & FDOPT_NOERRLOG) == 0) {
2566			disk_err(bp, "hard error",
2567			    fdc->fd->skip / DEV_BSIZE, 0);
2568			if (fdc->flags & FDC_STAT_VALID) {
2569				printf(
2570				" (ST0 %b ST1 %b ST2 %b cyl %u hd %u sec %u)\n",
2571				       fdc->status[0], NE7_ST0BITS,
2572				       fdc->status[1], NE7_ST1BITS,
2573				       fdc->status[2], NE7_ST2BITS,
2574				       fdc->status[3], fdc->status[4],
2575				       fdc->status[5]);
2576			}
2577			else
2578				printf(" (No status)\n");
2579		}
2580		if ((fd->options & FDOPT_NOERROR) == 0) {
2581			bp->bio_flags |= BIO_ERROR;
2582			bp->bio_error = EIO;
2583			bp->bio_resid = bp->bio_bcount - fdc->fd->skip;
2584		} else
2585			bp->bio_resid = 0;
2586		fdc->bp = NULL;
2587		fdc->fd->skip = 0;
2588		device_unbusy(fd->dev);
2589		biofinish(bp, fdc->fd->device_stats, 0);
2590		fdc->state = FINDWORK;
2591		fdc->flags |= FDC_NEEDS_RESET;
2592		fdc->fd = (fd_p) 0;
2593		fdc->fdu = -1;
2594		return (1);
2595	}
2596	fdc->retry++;
2597	return (1);
2598}
2599
2600static void
2601fdbiodone(struct bio *bp)
2602{
2603	wakeup(bp);
2604}
2605
2606static int
2607fdmisccmd(dev_t dev, u_int cmd, void *data)
2608{
2609 	fdu_t fdu;
2610 	fd_p fd;
2611	struct bio *bp;
2612	struct fd_formb *finfo;
2613	struct fdc_readid *idfield;
2614	size_t fdblk;
2615	int error;
2616
2617 	fdu = FDUNIT(minor(dev));
2618	fd = dev->si_drv1;
2619	fdblk = 128 << fd->ft->secsize;
2620	finfo = (struct fd_formb *)data;
2621	idfield = (struct fdc_readid *)data;
2622
2623	bp = malloc(sizeof(struct bio), M_TEMP, M_WAITOK | M_ZERO);
2624
2625	/*
2626	 * Set up a bio request for fdstrategy().  bio_offset is faked
2627	 * so that fdstrategy() will seek to the the requested
2628	 * cylinder, and use the desired head.
2629	 */
2630	bp->bio_cmd = cmd;
2631	if (cmd == FDBIO_FORMAT) {
2632		bp->bio_offset =
2633		    (finfo->cyl * (fd->ft->sectrac * fd->ft->heads) +
2634		     finfo->head * fd->ft->sectrac) * fdblk;
2635		bp->bio_bcount = sizeof(struct fd_idfield_data) *
2636		    finfo->fd_formb_nsecs;
2637	} else if (cmd == FDBIO_RDSECTID) {
2638		bp->bio_offset =
2639		    (idfield->cyl * (fd->ft->sectrac * fd->ft->heads) +
2640		     idfield->head * fd->ft->sectrac) * fdblk;
2641		bp->bio_bcount = sizeof(struct fdc_readid);
2642	} else
2643		panic("wrong cmd in fdmisccmd()");
2644	bp->bio_data = data;
2645	bp->bio_dev = dev;
2646	bp->bio_done = fdbiodone;
2647	bp->bio_flags = 0;
2648
2649	/* Now run the command. */
2650	fdstrategy(bp);
2651	error = biowait(bp, "fdcmd");
2652
2653	free(bp, M_TEMP);
2654	return (error);
2655}
2656
2657static int
2658fdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
2659{
2660 	fdu_t fdu;
2661 	fd_p fd;
2662	struct fdc_status *fsp;
2663	struct fdc_readid *rid;
2664	int error, type;
2665
2666 	fdu = FDUNIT(minor(dev));
2667	type = FDTYPE(minor(dev));
2668 	fd = dev->si_drv1;
2669
2670	/*
2671	 * First, handle everything that could be done with
2672	 * FD_NONBLOCK still being set.
2673	 */
2674	switch (cmd) {
2675
2676	case DIOCGMEDIASIZE:
2677		if (fd->ft == 0)
2678			return ((fd->flags & FD_NONBLOCK) ? EAGAIN : ENXIO);
2679		*(off_t *)addr = (128 << (fd->ft->secsize)) * fd->ft->size;
2680		return (0);
2681
2682	case DIOCGSECTORSIZE:
2683		if (fd->ft == 0)
2684			return ((fd->flags & FD_NONBLOCK) ? EAGAIN : ENXIO);
2685		*(u_int *)addr = 128 << (fd->ft->secsize);
2686		return (0);
2687
2688	case FIONBIO:
2689		if (*(int *)addr != 0)
2690			fd->flags |= FD_NONBLOCK;
2691		else {
2692			if (fd->ft == 0) {
2693				/*
2694				 * No drive type has been selected yet,
2695				 * cannot turn FNONBLOCK off.
2696				 */
2697				return (EINVAL);
2698			}
2699			fd->flags &= ~FD_NONBLOCK;
2700		}
2701		return (0);
2702
2703	case FIOASYNC:
2704		/* keep the generic fcntl() code happy */
2705		return (0);
2706
2707	case FD_GTYPE:                  /* get drive type */
2708		if (fd->ft == 0)
2709			/* no type known yet, return the native type */
2710			*(struct fd_type *)addr = fd_native_types[fd->type];
2711		else
2712			*(struct fd_type *)addr = *fd->ft;
2713		return (0);
2714
2715	case FD_STYPE:                  /* set drive type */
2716		if (type == 0) {
2717			/*
2718			 * Allow setting drive type temporarily iff
2719			 * currently unset.  Used for fdformat so any
2720			 * user can set it, and then start formatting.
2721			 */
2722			if (fd->ft)
2723				return (EINVAL); /* already set */
2724			fd->ft = fd->fts;
2725			*fd->ft = *(struct fd_type *)addr;
2726			fd->flags |= FD_UA;
2727		} else {
2728			/*
2729			 * Set density definition permanently.  Only
2730			 * allow for superuser.
2731			 */
2732			if (suser(td) != 0)
2733				return (EPERM);
2734			fd->fts[type] = *(struct fd_type *)addr;
2735		}
2736		return (0);
2737
2738	case FD_GOPTS:			/* get drive options */
2739		*(int *)addr = fd->options + (type == 0? FDOPT_AUTOSEL: 0);
2740		return (0);
2741
2742	case FD_SOPTS:			/* set drive options */
2743		fd->options = *(int *)addr & ~FDOPT_AUTOSEL;
2744		return (0);
2745
2746#ifdef FDC_DEBUG
2747	case FD_DEBUG:
2748		if ((fd_debug != 0) != (*(int *)addr != 0)) {
2749			fd_debug = (*(int *)addr != 0);
2750			printf("fd%d: debugging turned %s\n",
2751			    fd->fdu, fd_debug ? "on" : "off");
2752		}
2753		return (0);
2754#endif
2755
2756	case FD_CLRERR:
2757		if (suser(td) != 0)
2758			return (EPERM);
2759		fd->fdc->fdc_errs = 0;
2760		return (0);
2761
2762	case FD_GSTAT:
2763		fsp = (struct fdc_status *)addr;
2764		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
2765			return (EINVAL);
2766		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
2767		return (0);
2768
2769	case FD_GDTYPE:
2770		*(enum fd_drivetype *)addr = fd->type;
2771		return (0);
2772	}
2773
2774	/*
2775	 * Now handle everything else.  Make sure we have a valid
2776	 * drive type.
2777	 */
2778	if (fd->flags & FD_NONBLOCK)
2779		return (EAGAIN);
2780	if (fd->ft == 0)
2781		return (ENXIO);
2782	error = 0;
2783
2784	switch (cmd) {
2785
2786	case FD_FORM:
2787		if ((flag & FWRITE) == 0)
2788			return (EBADF);	/* must be opened for writing */
2789		if (((struct fd_formb *)addr)->format_version !=
2790		    FD_FORMAT_VERSION)
2791			return (EINVAL); /* wrong version of formatting prog */
2792		error = fdmisccmd(dev, FDBIO_FORMAT, addr);
2793		break;
2794
2795	case FD_GTYPE:                  /* get drive type */
2796		*(struct fd_type *)addr = *fd->ft;
2797		break;
2798
2799	case FD_STYPE:                  /* set drive type */
2800		/* this is considered harmful; only allow for superuser */
2801		if (suser(td) != 0)
2802			return (EPERM);
2803		*fd->ft = *(struct fd_type *)addr;
2804		break;
2805
2806	case FD_GOPTS:			/* get drive options */
2807		*(int *)addr = fd->options;
2808		break;
2809
2810	case FD_SOPTS:			/* set drive options */
2811		fd->options = *(int *)addr;
2812		break;
2813
2814#ifdef FDC_DEBUG
2815	case FD_DEBUG:
2816		if ((fd_debug != 0) != (*(int *)addr != 0)) {
2817			fd_debug = (*(int *)addr != 0);
2818			printf("fd%d: debugging turned %s\n",
2819			    fd->fdu, fd_debug ? "on" : "off");
2820		}
2821		break;
2822#endif
2823
2824	case FD_CLRERR:
2825		if (suser(td) != 0)
2826			return (EPERM);
2827		fd->fdc->fdc_errs = 0;
2828		break;
2829
2830	case FD_GSTAT:
2831		fsp = (struct fdc_status *)addr;
2832		if ((fd->fdc->flags & FDC_STAT_VALID) == 0)
2833			return (EINVAL);
2834		memcpy(fsp->status, fd->fdc->status, 7 * sizeof(u_int));
2835		break;
2836
2837	case FD_READID:
2838		rid = (struct fdc_readid *)addr;
2839		if (rid->cyl > MAX_CYLINDER || rid->head > MAX_HEAD)
2840			return (EINVAL);
2841		error = fdmisccmd(dev, FDBIO_RDSECTID, addr);
2842		break;
2843
2844	default:
2845		error = ENOTTY;
2846		break;
2847	}
2848	return (error);
2849}
2850