upgrade to linux 2.6.10-1.12_FC2
[linux-2.6.git] / drivers / ide / ide.c
1 /*
2  *  linux/drivers/ide/ide.c             Version 7.00beta2       Mar 05 2003
3  *
4  *  Copyright (C) 1994-1998  Linus Torvalds & authors (see below)
5  */
6
7 /*
8  *  Mostly written by Mark Lord  <mlord@pobox.com>
9  *                and Gadi Oxman <gadio@netvision.net.il>
10  *                and Andre Hedrick <andre@linux-ide.org>
11  *
12  *  See linux/MAINTAINERS for address of current maintainer.
13  *
14  * This is the multiple IDE interface driver, as evolved from hd.c.
15  * It supports up to MAX_HWIFS IDE interfaces, on one or more IRQs
16  *   (usually 14 & 15).
17  * There can be up to two drives per interface, as per the ATA-2 spec.
18  *
19  * Primary:    ide0, port 0x1f0; major=3;  hda is minor=0; hdb is minor=64
20  * Secondary:  ide1, port 0x170; major=22; hdc is minor=0; hdd is minor=64
21  * Tertiary:   ide2, port 0x???; major=33; hde is minor=0; hdf is minor=64
22  * Quaternary: ide3, port 0x???; major=34; hdg is minor=0; hdh is minor=64
23  * ...
24  *
25  *  From hd.c:
26  *  |
27  *  | It traverses the request-list, using interrupts to jump between functions.
28  *  | As nearly all functions can be called within interrupts, we may not sleep.
29  *  | Special care is recommended.  Have Fun!
30  *  |
31  *  | modified by Drew Eckhardt to check nr of hd's from the CMOS.
32  *  |
33  *  | Thanks to Branko Lankester, lankeste@fwi.uva.nl, who found a bug
34  *  | in the early extended-partition checks and added DM partitions.
35  *  |
36  *  | Early work on error handling by Mika Liljeberg (liljeber@cs.Helsinki.FI).
37  *  |
38  *  | IRQ-unmask, drive-id, multiple-mode, support for ">16 heads",
39  *  | and general streamlining by Mark Lord (mlord@pobox.com).
40  *
41  *  October, 1994 -- Complete line-by-line overhaul for linux 1.1.x, by:
42  *
43  *      Mark Lord       (mlord@pobox.com)               (IDE Perf.Pkg)
44  *      Delman Lee      (delman@ieee.org)               ("Mr. atdisk2")
45  *      Scott Snyder    (snyder@fnald0.fnal.gov)        (ATAPI IDE cd-rom)
46  *
47  *  This was a rewrite of just about everything from hd.c, though some original
48  *  code is still sprinkled about.  Think of it as a major evolution, with
49  *  inspiration from lots of linux users, esp.  hamish@zot.apana.org.au
50  *
51  *  Version 1.0 ALPHA   initial code, primary i/f working okay
52  *  Version 1.3 BETA    dual i/f on shared irq tested & working!
53  *  Version 1.4 BETA    added auto probing for irq(s)
54  *  Version 1.5 BETA    added ALPHA (untested) support for IDE cd-roms,
55  *  ...
56  * Version 5.50         allow values as small as 20 for idebus=
57  * Version 5.51         force non io_32bit in drive_cmd_intr()
58  *                      change delay_10ms() to delay_50ms() to fix problems
59  * Version 5.52         fix incorrect invalidation of removable devices
60  *                      add "hdx=slow" command line option
61  * Version 5.60         start to modularize the driver; the disk and ATAPI
62  *                       drivers can be compiled as loadable modules.
63  *                      move IDE probe code to ide-probe.c
64  *                      move IDE disk code to ide-disk.c
65  *                      add support for generic IDE device subdrivers
66  *                      add m68k code from Geert Uytterhoeven
67  *                      probe all interfaces by default
68  *                      add ioctl to (re)probe an interface
69  * Version 6.00         use per device request queues
70  *                      attempt to optimize shared hwgroup performance
71  *                      add ioctl to manually adjust bandwidth algorithms
72  *                      add kerneld support for the probe module
73  *                      fix bug in ide_error()
74  *                      fix bug in the first ide_get_lock() call for Atari
75  *                      don't flush leftover data for ATAPI devices
76  * Version 6.01         clear hwgroup->active while the hwgroup sleeps
77  *                      support HDIO_GETGEO for floppies
78  * Version 6.02         fix ide_ack_intr() call
79  *                      check partition table on floppies
80  * Version 6.03         handle bad status bit sequencing in ide_wait_stat()
81  * Version 6.10         deleted old entries from this list of updates
82  *                      replaced triton.c with ide-dma.c generic PCI DMA
83  *                      added support for BIOS-enabled UltraDMA
84  *                      rename all "promise" things to "pdc4030"
85  *                      fix EZ-DRIVE handling on small disks
86  * Version 6.11         fix probe error in ide_scan_devices()
87  *                      fix ancient "jiffies" polling bugs
88  *                      mask all hwgroup interrupts on each irq entry
89  * Version 6.12         integrate ioctl and proc interfaces
90  *                      fix parsing of "idex=" command line parameter
91  * Version 6.13         add support for ide4/ide5 courtesy rjones@orchestream.com
92  * Version 6.14         fixed IRQ sharing among PCI devices
93  * Version 6.15         added SMP awareness to IDE drivers
94  * Version 6.16         fixed various bugs; even more SMP friendly
95  * Version 6.17         fix for newest EZ-Drive problem
96  * Version 6.18         default unpartitioned-disk translation now "BIOS LBA"
97  * Version 6.19         Re-design for a UNIFORM driver for all platforms,
98  *                        model based on suggestions from Russell King and
99  *                        Geert Uytterhoeven
100  *                      Promise DC4030VL now supported.
101  *                      add support for ide6/ide7
102  *                      delay_50ms() changed to ide_delay_50ms() and exported.
103  * Version 6.20         Added/Fixed Generic ATA-66 support and hwif detection.
104  *                      Added hdx=flash to allow for second flash disk
105  *                        detection w/o the hang loop.
106  *                      Added support for ide8/ide9
107  *                      Added idex=ata66 for the quirky chipsets that are
108  *                        ATA-66 compliant, but have yet to determine a method
109  *                        of verification of the 80c cable presence.
110  *                        Specifically Promise's PDC20262 chipset.
111  * Version 6.21         Fixing/Fixed SMP spinlock issue with insight from an old
112  *                        hat that clarified original low level driver design.
113  * Version 6.30         Added SMP support; fixed multmode issues.  -ml
114  * Version 6.31         Debug Share INTR's and request queue streaming
115  *                      Native ATA-100 support
116  *                      Prep for Cascades Project
117  * Version 7.00alpha    First named revision of ide rearrange
118  *
119  *  Some additional driver compile-time options are in ./include/linux/ide.h
120  *
121  *  To do, in likely order of completion:
122  *      - modify kernel to obtain BIOS geometry for drives on 2nd/3rd/4th i/f
123  *
124  */
125
126 #define REVISION        "Revision: 7.00alpha2"
127 #define VERSION         "Id: ide.c 7.00a2 20020906"
128
129 #undef REALLY_SLOW_IO           /* most systems can safely undef this */
130
131 #define _IDE_C                  /* Tell ide.h it's really us */
132
133 #include <linux/config.h>
134 #include <linux/module.h>
135 #include <linux/types.h>
136 #include <linux/string.h>
137 #include <linux/kernel.h>
138 #include <linux/timer.h>
139 #include <linux/mm.h>
140 #include <linux/interrupt.h>
141 #include <linux/major.h>
142 #include <linux/errno.h>
143 #include <linux/genhd.h>
144 #include <linux/blkpg.h>
145 #include <linux/slab.h>
146 #include <linux/init.h>
147 #include <linux/pci.h>
148 #include <linux/delay.h>
149 #include <linux/ide.h>
150 #include <linux/devfs_fs_kernel.h>
151 #include <linux/completion.h>
152 #include <linux/reboot.h>
153 #include <linux/cdrom.h>
154 #include <linux/seq_file.h>
155 #include <linux/device.h>
156 #include <linux/bitops.h>
157
158 #include <asm/byteorder.h>
159 #include <asm/irq.h>
160 #include <asm/uaccess.h>
161 #include <asm/io.h>
162
163
164 /* default maximum number of failures */
165 #define IDE_DEFAULT_MAX_FAILURES        1
166
167 static const u8 ide_hwif_to_major[] = { IDE0_MAJOR, IDE1_MAJOR,
168                                         IDE2_MAJOR, IDE3_MAJOR,
169                                         IDE4_MAJOR, IDE5_MAJOR,
170                                         IDE6_MAJOR, IDE7_MAJOR,
171                                         IDE8_MAJOR, IDE9_MAJOR };
172
173 static int idebus_parameter;    /* holds the "idebus=" parameter */
174 static int system_bus_speed;    /* holds what we think is VESA/PCI bus speed */
175 static int initializing;        /* set while initializing built-in drivers */
176
177 DECLARE_MUTEX(ide_cfg_sem);
178 EXPORT_SYMBOL_GPL(ide_cfg_sem);
179 spinlock_t ide_lock __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
180
181 #ifdef CONFIG_BLK_DEV_IDEPCI
182 static int ide_scan_direction; /* THIS was formerly 2.2.x pci=reverse */
183 #endif
184
185 #ifdef CONFIG_IDEDMA_AUTO
186 int noautodma = 0;
187 #else
188 int noautodma = 1;
189 #endif
190
191 EXPORT_SYMBOL(noautodma);
192
193 /*
194  * This is declared extern in ide.h, for access by other IDE modules:
195  */
196 ide_hwif_t ide_hwifs[MAX_HWIFS];        /* master data repository */
197
198 EXPORT_SYMBOL(ide_hwifs);
199
200 extern ide_driver_t idedefault_driver;
201 static void setup_driver_defaults(ide_driver_t *driver);
202
203 /*
204  * Do not even *think* about calling this!
205  */
206 static void init_hwif_data(ide_hwif_t *hwif, unsigned int index)
207 {
208         unsigned int unit;
209         unsigned int key = hwif->key;
210
211         /* bulk initialize hwif & drive info with zeros */
212         memset(hwif, 0, sizeof(ide_hwif_t));
213
214         /* fill in any non-zero initial values */
215         hwif->key       = key + 1;      /* Protected by ide_cfg_sem */
216         hwif->index     = index;
217         hwif->major     = ide_hwif_to_major[index];
218
219         hwif->name[0]   = 'i';
220         hwif->name[1]   = 'd';
221         hwif->name[2]   = 'e';
222         hwif->name[3]   = '0' + index;
223
224         hwif->bus_state = BUSSTATE_ON;
225
226         hwif->atapi_dma = 0;            /* disable all atapi dma */ 
227         hwif->ultra_mask = 0x80;        /* disable all ultra */
228         hwif->mwdma_mask = 0x80;        /* disable all mwdma */
229         hwif->swdma_mask = 0x80;        /* disable all swdma */
230
231         sema_init(&hwif->gendev_rel_sem, 0);
232
233         default_hwif_iops(hwif);
234         default_hwif_transport(hwif);
235         for (unit = 0; unit < MAX_DRIVES; ++unit) {
236                 ide_drive_t *drive = &hwif->drives[unit];
237
238                 drive->media                    = ide_disk;
239                 drive->select.all               = (unit<<4)|0xa0;
240                 drive->hwif                     = hwif;
241                 drive->ctl                      = 0x08;
242                 drive->ready_stat               = READY_STAT;
243                 drive->bad_wstat                = BAD_W_STAT;
244                 drive->special.b.recalibrate    = 1;
245                 drive->special.b.set_geometry   = 1;
246                 drive->name[0]                  = 'h';
247                 drive->name[1]                  = 'd';
248                 drive->name[2]                  = 'a' + (index * MAX_DRIVES) + unit;
249                 drive->max_failures             = IDE_DEFAULT_MAX_FAILURES;
250                 drive->using_dma                = 0;
251                 drive->is_flash                 = 0;
252                 drive->driver                   = &idedefault_driver;
253                 drive->vdma                     = 0;
254                 INIT_LIST_HEAD(&drive->list);
255                 sema_init(&drive->gendev_rel_sem, 0);
256         }
257 }
258
259 static void init_hwif_default(ide_hwif_t *hwif, unsigned int index)
260 {
261         hw_regs_t hw;
262
263         memset(&hw, 0, sizeof(hw_regs_t));
264
265         ide_init_hwif_ports(&hw, ide_default_io_base(index), 0, &hwif->irq);
266
267         memcpy(&hwif->hw, &hw, sizeof(hw));
268         memcpy(hwif->io_ports, hw.io_ports, sizeof(hw.io_ports));
269
270         hwif->noprobe = !hwif->io_ports[IDE_DATA_OFFSET];
271 #ifdef CONFIG_BLK_DEV_HD
272         if (hwif->io_ports[IDE_DATA_OFFSET] == HD_DATA)
273                 hwif->noprobe = 1;      /* may be overridden by ide_setup() */
274 #endif
275 }
276
277 extern void ide_arm_init(void);
278
279 /*
280  * init_ide_data() sets reasonable default values into all fields
281  * of all instances of the hwifs and drives, but only on the first call.
282  * Subsequent calls have no effect (they don't wipe out anything).
283  *
284  * This routine is normally called at driver initialization time,
285  * but may also be called MUCH earlier during kernel "command-line"
286  * parameter processing.  As such, we cannot depend on any other parts
287  * of the kernel (such as memory allocation) to be functioning yet.
288  *
289  * This is too bad, as otherwise we could dynamically allocate the
290  * ide_drive_t structs as needed, rather than always consuming memory
291  * for the max possible number (MAX_HWIFS * MAX_DRIVES) of them.
292  *
293  * FIXME: We should stuff the setup data into __init and copy the
294  * relevant hwifs/allocate them properly during boot.
295  */
296 #define MAGIC_COOKIE 0x12345678
297 static void __init init_ide_data (void)
298 {
299         ide_hwif_t *hwif;
300         unsigned int index;
301         static unsigned long magic_cookie = MAGIC_COOKIE;
302
303         if (magic_cookie != MAGIC_COOKIE)
304                 return;         /* already initialized */
305         magic_cookie = 0;
306
307         setup_driver_defaults(&idedefault_driver);
308
309         /* Initialise all interface structures */
310         for (index = 0; index < MAX_HWIFS; ++index) {
311                 hwif = &ide_hwifs[index];
312                 init_hwif_data(hwif, index);
313                 init_hwif_default(hwif, index);
314 #if !defined(CONFIG_PPC32) || !defined(CONFIG_PCI)
315                 hwif->irq = hwif->hw.irq =
316                         ide_init_default_irq(hwif->io_ports[IDE_DATA_OFFSET]);
317 #endif
318         }
319 #ifdef CONFIG_IDE_ARM
320         initializing = 1;
321         ide_arm_init();
322         initializing = 0;
323 #endif
324 }
325
326 /*
327  *      ide_drive_from_key      -       turn key into drive
328  *      @kval: persistent key
329  *
330  *      Convert a key into a drive. Currently the key is packed as
331  *      [keyval] << 16 | hwif << 8 | drive_num. Caller must hold 
332  *      ide_settings_sem for the duration of the returned reference
333  */
334
335 ide_drive_t *ide_drive_from_key(void *kval)
336 {
337         unsigned long key = (unsigned long) kval;
338         int idx = (key >> 8) & 0xFF;
339         int drive = key & 3;
340         ide_hwif_t *hwif = &ide_hwifs[idx];
341         ide_drive_t *ret;
342
343         key >>= 16;
344
345         if(hwif->configured == 0 || hwif->present == 0 || hwif->drives[drive].dead || hwif->key != key)
346                 ret = NULL;
347         else
348                 ret = &ide_hwifs[idx].drives[drive];
349
350         return ret;
351 }
352
353 EXPORT_SYMBOL_GPL(ide_drive_from_key);
354
355 /*
356  *      ide_drive_to_key        -       turn drive to persistent key
357  *      @drive: drive to use
358  *
359  *      Convert drive into a key. Currently the key is packed as
360  *      [keyval] << 16 | hwif << 8 | drive_num. Caller must hold 
361  *      ide_settings_sem for the duration of the returned reference
362  */
363
364 void *ide_drive_to_key(ide_drive_t *drive)
365 {
366         ide_hwif_t *hwif = HWIF(drive);
367         unsigned long val;
368
369         val = (hwif->index << 8) | (hwif->key << 16) | drive->select.b.unit;
370         return (void *)val;
371 }
372
373 /*
374  *      ide_hwif_from_key       -       turn key into hwif
375  *      @kval: persistent key
376  *
377  *      Convert a key into a drive. Currently the key is packed as
378  *      [keyval] << 16 | hwif << 8 | drive_num. Caller must hold 
379  *      ide_settings_sem for the duration of the returned reference
380  */
381
382 ide_hwif_t *ide_hwif_from_key(void *kval)
383 {
384         unsigned long key = (unsigned long) kval;
385         int idx = (key >> 8) & 0xFF;
386         ide_hwif_t *hwif = &ide_hwifs[idx];
387
388         key >>= 16;
389
390         if(hwif->configured == 0 || hwif->present == 0 || hwif->key != key)
391                 return NULL;
392         return hwif;
393 }
394
395 /*
396  *      ide_hwif_to_key -       turn drive to persistent key
397  *      @hwif: hwif to use
398  *
399  *      Convert drive into a key. Currently the key is packed as
400  *      [keyval] << 16 | hwif << 8 | drive_num. Caller must hold 
401  *      ide_settings_sem for the duration of the returned reference
402  */
403
404 void *ide_hwif_to_key(ide_hwif_t *hwif)
405 {
406         unsigned long val;
407
408         val = (hwif->index << 8) | (hwif->key << 16);
409         return (void *)val;
410 }
411
412 /**
413  *      ide_system_bus_speed    -       guess bus speed
414  *
415  *      ide_system_bus_speed() returns what we think is the system VESA/PCI
416  *      bus speed (in MHz). This is used for calculating interface PIO timings.
417  *      The default is 40 for known PCI systems, 50 otherwise.
418  *      The "idebus=xx" parameter can be used to override this value.
419  *      The actual value to be used is computed/displayed the first time
420  *      through. Drivers should only use this as a last resort.
421  *
422  *      Returns a guessed speed in MHz.
423  */
424
425 int ide_system_bus_speed (void)
426 {
427         static struct pci_device_id pci_default[] = {
428                 { PCI_DEVICE(PCI_ANY_ID, PCI_ANY_ID) },
429                 { }
430         };
431
432         if (!system_bus_speed) {
433                 if (idebus_parameter) {
434                         /* user supplied value */
435                         system_bus_speed = idebus_parameter;
436                 } else if (pci_dev_present(pci_default)) {
437                         /* safe default value for PCI */
438                         system_bus_speed = 33;
439                 } else {
440                         /* safe default value for VESA and PCI */
441                         system_bus_speed = 50;
442                 }
443                 printk(KERN_INFO "ide: Assuming %dMHz system bus speed "
444                         "for PIO modes%s\n", system_bus_speed,
445                         idebus_parameter ? "" : "; override with idebus=xx");
446         }
447         return system_bus_speed;
448 }
449
450 /**
451  *      current_capacity        -       drive capacity
452  *      @drive: drive to query
453  *
454  *      Return the current capacity (in sectors) of a drive according to
455  *      its current geometry/LBA settings. Empty removables are reported
456  *      as size zero.
457  */
458
459 sector_t current_capacity (ide_drive_t *drive)
460 {
461         if (!drive->present)
462                 return 0;
463         return DRIVER(drive)->capacity(drive);
464 }
465
466 EXPORT_SYMBOL(current_capacity);
467
468 /**
469  *      ide_dump_status         -       translate ATA error
470  *      @drive: drive the error occured on
471  *      @msg: information string
472  *      @stat: status byte
473  *
474  *      Error reporting, in human readable form (luxurious, but a memory hog).
475  *      Combines the drive name, message and status byte to provide a
476  *      user understandable explanation of the device error.
477  */
478
479 u8 ide_dump_status (ide_drive_t *drive, const char *msg, u8 stat)
480 {
481         ide_hwif_t *hwif = HWIF(drive);
482         unsigned long flags;
483         u8 err = 0;
484
485         local_irq_set(flags);
486         printk(KERN_WARNING "%s: %s: status=0x%02x", drive->name, msg, stat);
487         printk(" { ");
488         if (stat & BUSY_STAT) {
489                 printk("Busy ");
490         } else {
491                 if (stat & READY_STAT)  printk("DriveReady ");
492                 if (stat & WRERR_STAT)  printk("DeviceFault ");
493                 if (stat & SEEK_STAT)   printk("SeekComplete ");
494                 if (stat & DRQ_STAT)    printk("DataRequest ");
495                 if (stat & ECC_STAT)    printk("CorrectedError ");
496                 if (stat & INDEX_STAT)  printk("Index ");
497                 if (stat & ERR_STAT)    printk("Error ");
498         }
499         printk("}");
500         printk("\n");
501         if ((stat & (BUSY_STAT|ERR_STAT)) == ERR_STAT) {
502                 err = hwif->INB(IDE_ERROR_REG);
503                 printk("%s: %s: error=0x%02x", drive->name, msg, err);
504                 if (drive->media == ide_disk) {
505                         printk(" { ");
506                         if (err & ABRT_ERR)     printk("DriveStatusError ");
507                         if (err & ICRC_ERR)     printk("Bad%s ", (err & ABRT_ERR) ? "CRC" : "Sector");
508                         if (err & ECC_ERR)      printk("UncorrectableError ");
509                         if (err & ID_ERR)       printk("SectorIdNotFound ");
510                         if (err & TRK0_ERR)     printk("TrackZeroNotFound ");
511                         if (err & MARK_ERR)     printk("AddrMarkNotFound ");
512                         printk("}");
513                         if ((err & (BBD_ERR | ABRT_ERR)) == BBD_ERR || (err & (ECC_ERR|ID_ERR|MARK_ERR))) {
514                                 if ((drive->id->command_set_2 & 0x0400) &&
515                                     (drive->id->cfs_enable_2 & 0x0400) &&
516                                     (drive->addressing == 1)) {
517                                         u64 sectors = 0;
518                                         u32 high = 0;
519                                         u32 low = ide_read_24(drive);
520                                         hwif->OUTB(drive->ctl|0x80, IDE_CONTROL_REG);
521                                         high = ide_read_24(drive);
522
523                                         sectors = ((u64)high << 24) | low;
524                                         printk(", LBAsect=%llu, high=%d, low=%d",
525                                                (long long) sectors,
526                                                high, low);
527                                 } else {
528                                         u8 cur = hwif->INB(IDE_SELECT_REG);
529                                         if (cur & 0x40) {       /* using LBA? */
530                                                 printk(", LBAsect=%ld", (unsigned long)
531                                                  ((cur&0xf)<<24)
532                                                  |(hwif->INB(IDE_HCYL_REG)<<16)
533                                                  |(hwif->INB(IDE_LCYL_REG)<<8)
534                                                  | hwif->INB(IDE_SECTOR_REG));
535                                         } else {
536                                                 printk(", CHS=%d/%d/%d",
537                                                  (hwif->INB(IDE_HCYL_REG)<<8) +
538                                                   hwif->INB(IDE_LCYL_REG),
539                                                   cur & 0xf,
540                                                   hwif->INB(IDE_SECTOR_REG));
541                                         }
542                                 }
543                                 if (HWGROUP(drive) && HWGROUP(drive)->rq)
544                                         printk(", sector=%llu", (unsigned long long)HWGROUP(drive)->rq->sector);
545                         }
546                 }
547                 printk("\n");
548         }
549         {
550                 struct request *rq;
551                 int opcode = 0x100;
552
553                 spin_lock(&ide_lock);
554                 rq = NULL;
555                 if (HWGROUP(drive))
556                         rq = HWGROUP(drive)->rq;
557                 spin_unlock(&ide_lock);
558                 if (!rq)
559                         goto out;
560                 if (rq->flags & (REQ_DRIVE_CMD | REQ_DRIVE_TASK)) {
561                         char *args = rq->buffer;
562                         if (args)
563                                 opcode = args[0];
564                 } else if (rq->flags & REQ_DRIVE_TASKFILE) {
565                         ide_task_t *args = rq->special;
566                         if (args) {
567                                 task_struct_t *tf = (task_struct_t *) args->tfRegister;
568                                 opcode = tf->command;
569                         }
570                 }
571
572                 printk("ide: failed opcode was %x\n", opcode);
573         }
574 out:
575         local_irq_restore(flags);
576         return err;
577 }
578
579 EXPORT_SYMBOL(ide_dump_status);
580
581 static int ide_open (struct inode * inode, struct file * filp)
582 {
583         return -ENXIO;
584 }
585
586 /*
587  *      drives_lock protects the list of drives, drivers lock the
588  *      list of drivers. Currently nobody takes both at once.
589  *      drivers_sem guards the drivers_list for readers that may
590  *      sleep. It must be taken before drivers_lock. Take drivers_sem
591  *      before ide_setting_sem and idecfg_sem before either of the
592  *      others.
593  */
594
595 static spinlock_t drives_lock = SPIN_LOCK_UNLOCKED;
596 static DECLARE_MUTEX(drivers_sem);
597 static spinlock_t drivers_lock = SPIN_LOCK_UNLOCKED;
598 static LIST_HEAD(drivers);
599
600 /* Iterator for the driver list. */
601
602 static void *m_start(struct seq_file *m, loff_t *pos)
603 {
604         struct list_head *p;
605         loff_t l = *pos;
606         down(&drivers_sem);
607         list_for_each(p, &drivers)
608                 if (!l--)
609                         return list_entry(p, ide_driver_t, drivers);
610         return NULL;
611 }
612
613 static void *m_next(struct seq_file *m, void *v, loff_t *pos)
614 {
615         struct list_head *p = ((ide_driver_t *)v)->drivers.next;
616         (*pos)++;
617         return p==&drivers ? NULL : list_entry(p, ide_driver_t, drivers);
618 }
619
620 static void m_stop(struct seq_file *m, void *v)
621 {
622         up(&drivers_sem);
623 }
624
625 static int show_driver(struct seq_file *m, void *v)
626 {
627         ide_driver_t *driver = v;
628         seq_printf(m, "%s version %s\n", driver->name, driver->version);
629         return 0;
630 }
631
632 struct seq_operations ide_drivers_op = {
633         .start  = m_start,
634         .next   = m_next,
635         .stop   = m_stop,
636         .show   = show_driver
637 };
638
639 #ifdef CONFIG_PROC_FS
640 struct proc_dir_entry *proc_ide_root;
641
642 ide_proc_entry_t generic_subdriver_entries[] = {
643         { "capacity",   S_IFREG|S_IRUGO,        proc_ide_read_capacity, NULL },
644         { NULL, 0, NULL, NULL }
645 };
646 #endif
647
648 static struct resource* hwif_request_region(ide_hwif_t *hwif,
649                                             unsigned long addr, int num)
650 {
651         struct resource *res = request_region(addr, num, hwif->name);
652
653         if (!res)
654                 printk(KERN_ERR "%s: I/O resource 0x%lX-0x%lX not free.\n",
655                                 hwif->name, addr, addr+num-1);
656         return res;
657 }
658
659 /**
660  *      ide_hwif_request_regions - request resources for IDE
661  *      @hwif: interface to use
662  *
663  *      Requests all the needed resources for an interface.
664  *      Right now core IDE code does this work which is deeply wrong.
665  *      MMIO leaves it to the controller driver,
666  *      PIO will migrate this way over time.
667  */
668
669 int ide_hwif_request_regions(ide_hwif_t *hwif)
670 {
671         unsigned long addr;
672         unsigned int i;
673
674         if (hwif->mmio == 2)
675                 return 0;
676         BUG_ON(hwif->mmio == 1);
677         addr = hwif->io_ports[IDE_CONTROL_OFFSET];
678         if (addr && !hwif_request_region(hwif, addr, 1))
679                 goto control_region_busy;
680         hwif->straight8 = 0;
681         addr = hwif->io_ports[IDE_DATA_OFFSET];
682         if ((addr | 7) == hwif->io_ports[IDE_STATUS_OFFSET]) {
683                 if (!hwif_request_region(hwif, addr, 8))
684                         goto data_region_busy;
685                 hwif->straight8 = 1;
686                 return 0;
687         }
688         for (i = IDE_DATA_OFFSET; i <= IDE_STATUS_OFFSET; i++) {
689                 addr = hwif->io_ports[i];
690                 if (!hwif_request_region(hwif, addr, 1)) {
691                         while (--i)
692                                 release_region(addr, 1);
693                         goto data_region_busy;
694                 }
695         }
696         return 0;
697
698 data_region_busy:
699         addr = hwif->io_ports[IDE_CONTROL_OFFSET];
700         if (addr)
701                 release_region(addr, 1);
702 control_region_busy:
703         /* If any errors are return, we drop the hwif interface. */
704         return -EBUSY;
705 }
706
707 /**
708  *      ide_hwif_release_regions - free IDE resources
709  *
710  *      Note that we only release the standard ports,
711  *      and do not even try to handle any extra ports
712  *      allocated for weird IDE interface chipsets.
713  *
714  *      Note also that we don't yet handle mmio resources here. More
715  *      importantly our caller should be doing this so we need to 
716  *      restructure this as a helper function for drivers.
717  */
718
719 void ide_hwif_release_regions(ide_hwif_t *hwif)
720 {
721         u32 i = 0;
722
723         if (hwif->mmio == 2)
724                 return;
725         if (hwif->io_ports[IDE_CONTROL_OFFSET])
726                 release_region(hwif->io_ports[IDE_CONTROL_OFFSET], 1);
727         if (hwif->straight8) {
728                 release_region(hwif->io_ports[IDE_DATA_OFFSET], 8);
729                 return;
730         }
731         for (i = IDE_DATA_OFFSET; i <= IDE_STATUS_OFFSET; i++)
732                 if (hwif->io_ports[i])
733                         release_region(hwif->io_ports[i], 1);
734 }
735
736 /**
737  *      ide_hwif_restore        -       restore hwif to template
738  *      @hwif: hwif to update
739  *      @tmp_hwif: template
740  *
741  *      Restore hwif to a previous state by copying most settngs
742  *      from the template.
743  */
744
745 static void ide_hwif_restore(ide_hwif_t *hwif, ide_hwif_t *tmp_hwif)
746 {
747         hwif->hwgroup                   = tmp_hwif->hwgroup;
748
749         hwif->gendev.parent             = tmp_hwif->gendev.parent;
750
751         hwif->proc                      = tmp_hwif->proc;
752
753         hwif->major                     = tmp_hwif->major;
754         hwif->straight8                 = tmp_hwif->straight8;
755         hwif->bus_state                 = tmp_hwif->bus_state;
756
757         hwif->atapi_dma                 = tmp_hwif->atapi_dma;
758         hwif->ultra_mask                = tmp_hwif->ultra_mask;
759         hwif->mwdma_mask                = tmp_hwif->mwdma_mask;
760         hwif->swdma_mask                = tmp_hwif->swdma_mask;
761
762         hwif->chipset                   = tmp_hwif->chipset;
763         hwif->hold                      = tmp_hwif->hold;
764
765 #ifdef CONFIG_BLK_DEV_IDEPCI
766         hwif->pci_dev                   = tmp_hwif->pci_dev;
767         hwif->cds                       = tmp_hwif->cds;
768 #endif
769
770         hwif->tuneproc                  = tmp_hwif->tuneproc;
771         hwif->speedproc                 = tmp_hwif->speedproc;
772         hwif->selectproc                = tmp_hwif->selectproc;
773         hwif->reset_poll                = tmp_hwif->reset_poll;
774         hwif->pre_reset                 = tmp_hwif->pre_reset;
775         hwif->resetproc                 = tmp_hwif->resetproc;
776         hwif->intrproc                  = tmp_hwif->intrproc;
777         hwif->maskproc                  = tmp_hwif->maskproc;
778         hwif->quirkproc                 = tmp_hwif->quirkproc;
779         hwif->busproc                   = tmp_hwif->busproc;
780
781         hwif->ata_input_data            = tmp_hwif->ata_input_data;
782         hwif->ata_output_data           = tmp_hwif->ata_output_data;
783         hwif->atapi_input_bytes         = tmp_hwif->atapi_input_bytes;
784         hwif->atapi_output_bytes        = tmp_hwif->atapi_output_bytes;
785
786         hwif->ide_dma_setup             = tmp_hwif->ide_dma_setup;
787         hwif->ide_dma_exec_cmd          = tmp_hwif->ide_dma_exec_cmd;
788         hwif->ide_dma_start             = tmp_hwif->ide_dma_start;
789         hwif->ide_dma_end               = tmp_hwif->ide_dma_end;
790         hwif->ide_dma_check             = tmp_hwif->ide_dma_check;
791         hwif->ide_dma_on                = tmp_hwif->ide_dma_on;
792         hwif->ide_dma_off_quietly       = tmp_hwif->ide_dma_off_quietly;
793         hwif->ide_dma_test_irq          = tmp_hwif->ide_dma_test_irq;
794         hwif->ide_dma_host_on           = tmp_hwif->ide_dma_host_on;
795         hwif->ide_dma_host_off          = tmp_hwif->ide_dma_host_off;
796         hwif->ide_dma_lostirq           = tmp_hwif->ide_dma_lostirq;
797         hwif->ide_dma_timeout           = tmp_hwif->ide_dma_timeout;
798
799         hwif->OUTB                      = tmp_hwif->OUTB;
800         hwif->OUTBSYNC                  = tmp_hwif->OUTBSYNC;
801         hwif->OUTW                      = tmp_hwif->OUTW;
802         hwif->OUTL                      = tmp_hwif->OUTL;
803         hwif->OUTSW                     = tmp_hwif->OUTSW;
804         hwif->OUTSL                     = tmp_hwif->OUTSL;
805
806         hwif->INB                       = tmp_hwif->INB;
807         hwif->INW                       = tmp_hwif->INW;
808         hwif->INL                       = tmp_hwif->INL;
809         hwif->INSW                      = tmp_hwif->INSW;
810         hwif->INSL                      = tmp_hwif->INSL;
811
812         hwif->sg_max_nents              = tmp_hwif->sg_max_nents;
813
814         hwif->mmio                      = tmp_hwif->mmio;
815         hwif->rqsize                    = tmp_hwif->rqsize;
816         hwif->no_lba48                  = tmp_hwif->no_lba48;
817
818 #ifndef CONFIG_BLK_DEV_IDECS
819         hwif->irq                       = tmp_hwif->irq;
820 #endif
821
822         hwif->dma_base                  = tmp_hwif->dma_base;
823         hwif->dma_master                = tmp_hwif->dma_master;
824         hwif->dma_command               = tmp_hwif->dma_command;
825         hwif->dma_vendor1               = tmp_hwif->dma_vendor1;
826         hwif->dma_status                = tmp_hwif->dma_status;
827         hwif->dma_vendor3               = tmp_hwif->dma_vendor3;
828         hwif->dma_prdtable              = tmp_hwif->dma_prdtable;
829
830         hwif->dma_extra                 = tmp_hwif->dma_extra;
831         hwif->config_data               = tmp_hwif->config_data;
832         hwif->select_data               = tmp_hwif->select_data;
833         hwif->autodma                   = tmp_hwif->autodma;
834         hwif->udma_four                 = tmp_hwif->udma_four;
835         hwif->no_dsc                    = tmp_hwif->no_dsc;
836
837         hwif->hwif_data                 = tmp_hwif->hwif_data;
838 }
839
840 /**
841  *      __ide_unregister_hwif   -       free an ide interface
842  *      @hwif: interface to unregister
843  *
844  *      Perform the final unregister of an IDE interface. At the moment
845  *      we don't refcount interfaces so this will also get split up.
846  *
847  *      Locking:
848  *      The caller must not hold the IDE locks except for ide_cfg_sem
849  *      which must be held.
850  *
851  *      The drive present/vanishing is not yet properly locked
852  *      Take care with the callbacks. These have been split to avoid
853  *      deadlocking the IDE layer. The shutdown callback is called
854  *      before we take the lock and free resources. It is up to the
855  *      caller to be sure there is no pending I/O here, and that
856  *      the interfce will not be reopened (present/vanishing locking
857  *      isnt yet done btw). After we commit to the final kill we
858  *      call the cleanup callback with the ide locks held.
859  *
860  *      An interface can be in four states we care about
861  *      - It can be busy (drive or driver thinks its active). No unload
862  *      - It can be unconfigured - which means its already gone
863  *      - It can be configured and present - a full interface
864  *      - It can be configured and not present - pci configured but no drives
865  *                                               so logically absent.
866  *
867  *      Unregister restores the hwif structures to the default state.
868  */
869
870 int __ide_unregister_hwif(ide_hwif_t *hwif)
871 {
872         ide_drive_t *drive = NULL; /* keep compiler happy */
873         ide_hwif_t *g;
874         static ide_hwif_t tmp_hwif; /* protected by ide_cfg_sem */
875         ide_hwgroup_t *hwgroup;
876         int irq_count = 0, unit, i;
877         int was_present;
878         int ret = 0;
879         int index = hwif->index;
880
881         BUG_ON(in_interrupt());
882         BUG_ON(irqs_disabled());
883
884         /* Make sure nobody sneaks in via the proc interface */ 
885         down(&ide_setting_sem);
886         
887         /* Now ensure nobody gets in for I/O while we clean up and
888            do the busy check. If busy is set then the device is still
889            open and we must stop */
890         spin_lock_irq(&ide_lock);
891         
892         if (!hwif->configured)
893                 goto abort;
894         for (unit = 0; unit < MAX_DRIVES; ++unit) {
895                 drive = &hwif->drives[unit];
896                 if (!drive->present)
897                         continue;
898                 if (drive->usage || DRIVER(drive)->busy)
899                         goto abort;
900                 drive->dead = 1;
901         }
902         /* 
903          * Protect against new users. From this point the hwif
904          * is not present so cannot be opened by a new I/O source.
905          * This also invalidates key driven access from procfs
906          */
907
908         was_present = hwif->present;     
909         hwif->present = 0;
910
911         spin_unlock_irq(&ide_lock);
912         up(&ide_setting_sem);
913
914         for (unit = 0; unit < MAX_DRIVES; ++unit) {
915                 drive = &hwif->drives[unit];
916                 if (!drive->present)
917                         continue;
918                 DRIVER(drive)->cleanup(drive);
919         }
920
921         destroy_proc_ide_interface(hwif);
922
923         spin_lock_irq(&ide_lock);
924         hwgroup = hwif->hwgroup;
925         if(hwgroup)
926         {
927                 /*
928                  * free the irq if we were the only hwif using it
929                  */
930                 g = hwgroup->hwif;
931                 do {
932                         if (g->irq == hwif->irq)
933                                 ++irq_count;
934                         g = g->next;
935                 } while (g != hwgroup->hwif);
936         }
937         spin_unlock_irq(&ide_lock);
938         
939         if (irq_count == 1 && hwgroup)
940                 free_irq(hwif->irq, hwgroup);
941
942         /*
943          * Note that we only release the standard ports,
944          * and do not even try to handle any extra ports
945          * allocated for weird IDE interface chipsets.
946          *
947          * FIXME: should defer this I think
948          */
949
950         if(was_present)
951                 ide_hwif_release_regions(hwif);
952         /*
953          * Remove us from the hwgroup, and free
954          * the hwgroup if we were the only member
955          */
956         for (i = 0; i < MAX_DRIVES; ++i) {
957                 drive = &hwif->drives[i];
958                 if (drive->devfs_name[0] != '\0') {
959                         devfs_remove(drive->devfs_name);
960                         drive->devfs_name[0] = '\0';
961                 }
962                 if (!drive->present)
963                         continue;
964                         
965                 /*
966                  * The hwgroup chain is IRQ touched. We must protect
967                  * walking this from an IDE event for another device
968                  * in the chain 
969                  */
970                    
971                 spin_lock_irq(&ide_lock);
972                 if (drive == drive->next) {
973                         /* special case: last drive from hwgroup. */
974                         BUG_ON(hwgroup->drive != drive);
975                         hwgroup->drive = NULL;
976                 } else {
977                         ide_drive_t *walk;
978
979                         walk = hwgroup->drive;
980                         while (walk->next != drive)
981                                 walk = walk->next;
982                         walk->next = drive->next;
983                         if (hwgroup->drive == drive) {
984                                 hwgroup->drive = drive->next;
985                                 hwgroup->hwif = HWIF(hwgroup->drive);
986                         }
987                 }
988                 spin_unlock_irq(&ide_lock);
989
990                 /*
991                  * The rest of the cleanup is private
992                  */
993
994                 BUG_ON(hwgroup->drive == drive);
995                 if (drive->id != NULL) {
996                         kfree(drive->id);
997                         drive->id = NULL;
998                 }
999                 drive->present = 0;
1000                 blk_cleanup_queue(drive->queue);
1001                 device_unregister(&drive->gendev);
1002                 down(&drive->gendev_rel_sem);
1003                 drive->queue = NULL;
1004         }
1005         /*
1006          * Lock against hwgroup walkers including interrupts off other
1007          * IDE devices wile we unhook ourselves.
1008          */
1009          
1010         spin_lock_irq(&ide_lock);
1011         
1012         if (hwgroup)
1013         {
1014                 if (hwif->next == hwif) {
1015                         BUG_ON(hwgroup->hwif != hwif);
1016                         kfree(hwgroup);
1017                 } else {
1018                         /* There is another interface in hwgroup.
1019                          * Unlink us, and set hwgroup->drive and ->hwif to
1020                          * something sane.
1021                          */
1022                         g = hwgroup->hwif;
1023                         while (g->next != hwif)
1024                                 g = g->next;
1025                         g->next = hwif->next;
1026                         if (hwgroup->hwif == hwif) {
1027                                 /* Chose a random hwif for hwgroup->hwif.
1028                                  * It's guaranteed that there are no drives
1029                                  * left in the hwgroup.
1030                                  */
1031                                 BUG_ON(hwgroup->drive != NULL);
1032                                 hwgroup->hwif = g;
1033                         }
1034                         BUG_ON(hwgroup->hwif == hwif);
1035                 }
1036         }
1037         spin_unlock_irq(&ide_lock);
1038
1039         /*
1040          * PCI interfaces with no devices don't exist in the device
1041          * tree so don't unregister them.
1042          */
1043          
1044         if(was_present)
1045         {
1046                 device_unregister(&hwif->gendev);
1047                 down(&hwif->gendev_rel_sem);
1048         }
1049
1050         /*
1051          * Remove us from the kernel's knowledge
1052          */
1053         blk_unregister_region(MKDEV(hwif->major, 0), MAX_DRIVES<<PARTN_BITS);
1054         for (i = 0; i < MAX_DRIVES; i++) {
1055                 struct gendisk *disk = hwif->drives[i].disk;
1056                 hwif->drives[i].disk = NULL;
1057                 put_disk(disk);
1058         }
1059         kfree(hwif->sg_table);
1060         unregister_blkdev(hwif->major, hwif->name);
1061         spin_lock_irq(&ide_lock);
1062
1063         /*
1064          * Let the driver free up private objects
1065          */
1066
1067         if(hwif->remove)
1068                 hwif->remove(hwif);
1069
1070         if (hwif->dma_base) {
1071                 (void) ide_release_dma(hwif);
1072
1073                 hwif->dma_base = 0;
1074                 hwif->dma_master = 0;
1075                 hwif->dma_command = 0;
1076                 hwif->dma_vendor1 = 0;
1077                 hwif->dma_status = 0;
1078                 hwif->dma_vendor3 = 0;
1079                 hwif->dma_prdtable = 0;
1080         }
1081         hwif->chipset = ide_unknown;
1082
1083         /* copy original settings */
1084         tmp_hwif = *hwif;
1085
1086         /* restore hwif data to pristine status */
1087         init_hwif_data(hwif, index);
1088         init_hwif_default(hwif, index);
1089
1090         hwif->configured = 0;
1091
1092         ide_hwif_restore(hwif, &tmp_hwif);
1093         
1094         spin_unlock_irq(&ide_lock);
1095         return 0;
1096
1097 abort:
1098         if(hwif->configured)
1099         {
1100                 printk("Unregister %d fail %d %d\n", index, drive->usage, DRIVER(drive)->busy);
1101                 ret = -EBUSY;
1102         }
1103         else
1104         {
1105                 printk("No such hwif!\n");
1106                 ret = -ENOENT;
1107         }
1108         spin_unlock_irq(&ide_lock);
1109         up(&ide_setting_sem);
1110         return ret;
1111 }
1112
1113 EXPORT_SYMBOL_GPL(__ide_unregister_hwif);
1114
1115 /**
1116  *      ide_unregister_hwif     -       free an ide interface
1117  *      @hwif: interface to unregister
1118  *
1119  *      Perform the final unregister of an IDE interface. At the moment
1120  *      we don't refcount interfaces so this will also get split up.
1121  *      Unregister restores the hwif structures to the default state.
1122  *
1123  *      No locks should be held on entry. When an unregister must
1124  *      be done atomically with a register see __ide_unregister_hwif
1125  *      and hold the ide_cfg_sem yourself.
1126  */
1127
1128 int ide_unregister_hwif(ide_hwif_t *hwif)
1129 {
1130         int ret;
1131         
1132         /* This protects two things. Firstly it serializes the 
1133            shutdown sequence, secondly it protects us from
1134            races while we are killing off a device */
1135         down(&ide_cfg_sem);
1136         ret = __ide_unregister_hwif(hwif);
1137         up(&ide_cfg_sem);
1138         return ret;
1139 }
1140
1141 EXPORT_SYMBOL_GPL(ide_unregister_hwif);
1142
1143 /**
1144  *      ide_setup_ports         -       set up IDE interface ports
1145  *      @hw: register descriptions
1146  *      @base: base register
1147  *      @offsets: table of register offsets
1148  *      @ctrl: control register
1149  *      @ack_irq: IRQ ack
1150  *      @irq: interrupt lie
1151  *
1152  *      Setup hw_regs_t structure described by parameters.  You
1153  *      may set up the hw structure yourself OR use this routine to
1154  *      do it for you. This is basically a helper
1155  *
1156  */
1157  
1158 void ide_setup_ports (  hw_regs_t *hw,
1159                         unsigned long base, int *offsets,
1160                         unsigned long ctrl, unsigned long intr,
1161                         ide_ack_intr_t *ack_intr,
1162 /*
1163  *                      ide_io_ops_t *iops,
1164  */
1165                         int irq)
1166 {
1167         int i;
1168
1169         for (i = 0; i < IDE_NR_PORTS; i++) {
1170                 if (offsets[i] == -1) {
1171                         switch(i) {
1172                                 case IDE_CONTROL_OFFSET:
1173                                         hw->io_ports[i] = ctrl;
1174                                         break;
1175 #if defined(CONFIG_AMIGA) || defined(CONFIG_MAC)
1176                                 case IDE_IRQ_OFFSET:
1177                                         hw->io_ports[i] = intr;
1178                                         break;
1179 #endif /* (CONFIG_AMIGA) || (CONFIG_MAC) */
1180                                 default:
1181                                         hw->io_ports[i] = 0;
1182                                         break;
1183                         }
1184                 } else {
1185                         hw->io_ports[i] = base + offsets[i];
1186                 }
1187         }
1188         hw->irq = irq;
1189         hw->dma = NO_DMA;
1190         hw->ack_intr = ack_intr;
1191 /*
1192  *      hw->iops = iops;
1193  */
1194 }
1195
1196 /**
1197  *      ide_register_hw_with_fixup      -       register IDE interface
1198  *      @hw: hardware registers
1199  *      @hwifp: pointer to returned hwif
1200  *      @fixup: fixup function
1201  *
1202  *      Register an IDE interface, specifying exactly the registers etc.
1203  *      Set init=1 iff calling before probes have taken place. The
1204  *      ide_cfg_sem protects this against races.
1205  *
1206  *      Invokes a fixup function after the probe and before device attachment
1207  *      that can be used by the driver to amend settings or to work around
1208  *      hardware funnies.
1209  *
1210  *      Returns -1 on error.
1211  */
1212
1213 int ide_register_hw_with_fixup(hw_regs_t *hw, ide_hwif_t **hwifp, void(*fixup)(ide_hwif_t *hwif))
1214 {
1215         int index, retry = 1;
1216         ide_hwif_t *hwif;
1217
1218         down(&ide_cfg_sem);
1219
1220         do {
1221                 for (index = 0; index < MAX_HWIFS; ++index) {
1222                         hwif = &ide_hwifs[index];
1223                         if (hwif->hw.io_ports[IDE_DATA_OFFSET] == hw->io_ports[IDE_DATA_OFFSET])
1224                                 goto found;
1225                 }
1226                 for (index = 0; index < MAX_HWIFS; ++index) {
1227                         hwif = &ide_hwifs[index];
1228                         if (hwif->hold)
1229                                 continue;
1230                         if ((!hwif->configured && !hwif->mate && !initializing) ||
1231                             (!hwif->hw.io_ports[IDE_DATA_OFFSET] && initializing))
1232                                 goto found;
1233                 }
1234                 /* FIXME- this check should die as should the retry loop */
1235                 for (index = 0; index < MAX_HWIFS; index++) {
1236                         hwif = &ide_hwifs[index];
1237                         __ide_unregister_hwif(hwif);
1238                 }
1239         } while (retry--);
1240
1241         up(&ide_cfg_sem);
1242         return -1;
1243 found:
1244         /* FIXME: do we really need this case */
1245         if (hwif->configured)
1246                 __ide_unregister_hwif(hwif);
1247         else if (!hwif->hold) {
1248                 init_hwif_data(hwif, index);
1249                 init_hwif_default(hwif, index);
1250         }
1251         if (hwif->configured)
1252                 return -1;
1253         hwif->configured = 1;
1254         memcpy(&hwif->hw, hw, sizeof(*hw));
1255         memcpy(hwif->io_ports, hwif->hw.io_ports, sizeof(hwif->hw.io_ports));
1256         hwif->irq = hw->irq;
1257         hwif->noprobe = 0;
1258         hwif->chipset = hw->chipset;
1259         up(&ide_cfg_sem);
1260
1261         if (!initializing) {
1262                 probe_hwif_init_with_fixup(hwif, fixup);
1263                 create_proc_ide_interfaces();
1264         }
1265
1266         if (hwifp)
1267                 *hwifp = hwif;
1268
1269         return (initializing || hwif->present) ? index : -1;
1270 }
1271
1272 EXPORT_SYMBOL(ide_register_hw_with_fixup);
1273
1274 int ide_register_hw(hw_regs_t *hw, ide_hwif_t **hwifp)
1275 {
1276         return ide_register_hw_with_fixup(hw, hwifp, NULL);
1277 }
1278
1279 EXPORT_SYMBOL(ide_register_hw);
1280
1281 /*
1282  *      Locks for IDE setting functionality
1283  */
1284
1285 DECLARE_MUTEX(ide_setting_sem);
1286
1287 /**
1288  *      ide_add_setting -       add an ide setting option
1289  *      @drive: drive to use
1290  *      @name: setting name
1291  *      @rw: true if the function is read write
1292  *      @read_ioctl: function to call on read
1293  *      @write_ioctl: function to call on write
1294  *      @data_type: type of data
1295  *      @min: range minimum
1296  *      @max: range maximum
1297  *      @mul_factor: multiplication scale
1298  *      @div_factor: divison scale
1299  *      @data: private data field
1300  *      @set: setting
1301  *
1302  *      Removes the setting named from the device if it is present.
1303  *      This function must not be called from IRQ context. Returns 0
1304  *      on success or -1 on failure.
1305  *
1306  *      BUGS: This code is seriously over-engineered. There is also
1307  *      magic about how the driver specific features are setup. If
1308  *      a driver is attached we assume the driver settings are auto
1309  *      remove.
1310  *
1311  *      The caller must hold settings_lock
1312  */
1313  
1314 int ide_add_setting (ide_drive_t *drive, const char *name, int rw, int read_ioctl, int write_ioctl, int data_type, int min, int max, int mul_factor, int div_factor, void *data, ide_procset_t *set)
1315 {
1316         ide_settings_t **p = (ide_settings_t **) &drive->settings, *setting = NULL;
1317
1318         while ((*p) && strcmp((*p)->name, name) < 0)
1319                 p = &((*p)->next);
1320         if ((setting = kmalloc(sizeof(*setting), GFP_KERNEL)) == NULL)
1321                 goto abort;
1322         memset(setting, 0, sizeof(*setting));
1323         if ((setting->name = kmalloc(strlen(name) + 1, GFP_KERNEL)) == NULL)
1324                 goto abort;
1325         strcpy(setting->name, name);
1326         setting->rw = rw;
1327         setting->read_ioctl = read_ioctl;
1328         setting->write_ioctl = write_ioctl;
1329         setting->data_type = data_type;
1330         setting->min = min;
1331         setting->max = max;
1332         setting->mul_factor = mul_factor;
1333         setting->div_factor = div_factor;
1334         setting->data = data;
1335         setting->set = set;
1336         
1337         setting->next = *p;
1338         if (drive->driver != &idedefault_driver)
1339                 setting->auto_remove = 1;
1340         *p = setting;
1341         return 0;
1342 abort:
1343         if (setting)
1344                 kfree(setting);
1345         return -1;
1346 }
1347
1348 EXPORT_SYMBOL(ide_add_setting);
1349
1350 /**
1351  *      ide_remove_setting      -       remove an ide setting option
1352  *      @drive: drive to use
1353  *      @name: setting name
1354  *
1355  *      Removes the setting named from the device if it is present.
1356  *      The caller must hold the setting semaphore.
1357  */
1358  
1359 static void ide_remove_setting (ide_drive_t *drive, char *name)
1360 {
1361         ide_settings_t **p, *setting;
1362
1363         p = (ide_settings_t **) &drive->settings;
1364
1365         while ((*p) && strcmp((*p)->name, name))
1366                 p = &((*p)->next);
1367         if ((setting = (*p)) == NULL)
1368                 return;
1369
1370         (*p) = setting->next;
1371         
1372         kfree(setting->name);
1373         kfree(setting);
1374 }
1375
1376 /**
1377  *      ide_find_setting_by_ioctl       -       find a drive specific ioctl
1378  *      @drive: drive to scan
1379  *      @cmd: ioctl command to handle
1380  *
1381  *      Scan's the device setting table for a matching entry and returns
1382  *      this or NULL if no entry is found. The caller must hold the
1383  *      setting semaphore
1384  */
1385  
1386 static ide_settings_t *ide_find_setting_by_ioctl (ide_drive_t *drive, int cmd)
1387 {
1388         ide_settings_t *setting = drive->settings;
1389
1390         while (setting) {
1391                 if (setting->read_ioctl == cmd || setting->write_ioctl == cmd)
1392                         break;
1393                 setting = setting->next;
1394         }
1395         
1396         return setting;
1397 }
1398
1399 /**
1400  *      ide_find_setting_by_name        -       find a drive specific setting
1401  *      @drive: drive to scan
1402  *      @name: setting name
1403  *
1404  *      Scan's the device setting table for a matching entry and returns
1405  *      this or NULL if no entry is found. The caller must hold the
1406  *      setting semaphore
1407  */
1408  
1409 ide_settings_t *ide_find_setting_by_name (ide_drive_t *drive, char *name)
1410 {
1411         ide_settings_t *setting = drive->settings;
1412
1413         while (setting) {
1414                 if (strcmp(setting->name, name) == 0)
1415                         break;
1416                 setting = setting->next;
1417         }
1418         return setting;
1419 }
1420
1421 /**
1422  *      auto_remove_settings    -       remove driver specific settings
1423  *      @drive: drive
1424  *
1425  *      Automatically remove all the driver specific settings for this
1426  *      drive. This function may sleep and must not be called from IRQ
1427  *      context. The caller must hold ide_setting_sem.
1428  */
1429  
1430 static void auto_remove_settings (ide_drive_t *drive)
1431 {
1432         ide_settings_t *setting;
1433 repeat:
1434         setting = drive->settings;
1435         while (setting) {
1436                 if (setting->auto_remove) {
1437                         ide_remove_setting(drive, setting->name);
1438                         goto repeat;
1439                 }
1440                 setting = setting->next;
1441         }
1442 }
1443
1444 /**
1445  *      ide_read_setting        -       read an IDE setting
1446  *      @drive: drive to read from
1447  *      @setting: drive setting
1448  *
1449  *      Read a drive setting and return the value. The caller
1450  *      must hold the ide_setting_sem when making this call.
1451  *
1452  *      BUGS: the data return and error are the same return value
1453  *      so an error -EINVAL and true return of the same value cannot
1454  *      be told apart
1455  */
1456  
1457 int ide_read_setting (ide_drive_t *drive, ide_settings_t *setting)
1458 {
1459         int             val = -EINVAL;
1460         unsigned long   flags;
1461
1462         if ((setting->rw & SETTING_READ)) {
1463                 spin_lock_irqsave(&ide_lock, flags);
1464                 switch(setting->data_type) {
1465                         case TYPE_BYTE:
1466                                 val = *((u8 *) setting->data);
1467                                 break;
1468                         case TYPE_SHORT:
1469                                 val = *((u16 *) setting->data);
1470                                 break;
1471                         case TYPE_INT:
1472                         case TYPE_INTA:
1473                                 val = *((u32 *) setting->data);
1474                                 break;
1475                 }
1476                 spin_unlock_irqrestore(&ide_lock, flags);
1477         }
1478         return val;
1479 }
1480
1481 /**
1482  *      ide_spin_wait_hwgroup   -       wait for group
1483  *      @drive: drive in the group
1484  *
1485  *      Wait for an IDE device group to go non busy and then return
1486  *      holding the ide_lock which guards the hwgroup->busy status
1487  *      and right to use it.
1488  */
1489
1490 int ide_spin_wait_hwgroup (ide_drive_t *drive)
1491 {
1492         ide_hwgroup_t *hwgroup = HWGROUP(drive);
1493         unsigned long timeout = jiffies + (3 * HZ);
1494
1495         spin_lock_irq(&ide_lock);
1496
1497         while (hwgroup->busy) {
1498                 unsigned long lflags;
1499                 spin_unlock_irq(&ide_lock);
1500                 local_irq_set(lflags);
1501                 if (time_after(jiffies, timeout)) {
1502                         local_irq_restore(lflags);
1503                         printk(KERN_ERR "%s: channel busy\n", drive->name);
1504                         return -EBUSY;
1505                 }
1506                 local_irq_restore(lflags);
1507                 spin_lock_irq(&ide_lock);
1508         }
1509         return 0;
1510 }
1511
1512 EXPORT_SYMBOL(ide_spin_wait_hwgroup);
1513
1514 /**
1515  *      ide_write_setting       -       read an IDE setting
1516  *      @drive: drive to read from
1517  *      @setting: drive setting
1518  *      @val: value
1519  *
1520  *      Write a drive setting if it is possible. The caller
1521  *      must hold the ide_setting_sem when making this call.
1522  *
1523  *      BUGS: the data return and error are the same return value
1524  *      so an error -EINVAL and true return of the same value cannot
1525  *      be told apart
1526  *
1527  *      FIXME:  This should be changed to enqueue a special request
1528  *      to the driver to change settings, and then wait on a sema for completion.
1529  *      The current scheme of polling is kludgy, though safe enough.
1530  */
1531
1532 int ide_write_setting (ide_drive_t *drive, ide_settings_t *setting, int val)
1533 {
1534         int i;
1535         u32 *p;
1536
1537         if (!capable(CAP_SYS_ADMIN))
1538                 return -EACCES;
1539         if (!(setting->rw & SETTING_WRITE))
1540                 return -EPERM;
1541         if (val < setting->min || val > setting->max)
1542                 return -EINVAL;
1543         if (setting->set)
1544                 return setting->set(drive, val);
1545         if (ide_spin_wait_hwgroup(drive))
1546                 return -EBUSY;
1547         switch (setting->data_type) {
1548                 case TYPE_BYTE:
1549                         *((u8 *) setting->data) = val;
1550                         break;
1551                 case TYPE_SHORT:
1552                         *((u16 *) setting->data) = val;
1553                         break;
1554                 case TYPE_INT:
1555                         *((u32 *) setting->data) = val;
1556                         break;
1557                 case TYPE_INTA:
1558                         p = (u32 *) setting->data;
1559                         for (i = 0; i < 1 << PARTN_BITS; i++, p++)
1560                                 *p = val;
1561                         break;
1562         }
1563         spin_unlock_irq(&ide_lock);
1564         return 0;
1565 }
1566
1567 static int set_io_32bit(ide_drive_t *drive, int arg)
1568 {
1569         drive->io_32bit = arg;
1570 #ifdef CONFIG_BLK_DEV_DTC2278
1571         if (HWIF(drive)->chipset == ide_dtc2278)
1572                 HWIF(drive)->drives[!drive->select.b.unit].io_32bit = arg;
1573 #endif /* CONFIG_BLK_DEV_DTC2278 */
1574         return 0;
1575 }
1576
1577 static int set_using_dma (ide_drive_t *drive, int arg)
1578 {
1579 #ifdef CONFIG_BLK_DEV_IDEDMA
1580         if (!drive->id || !(drive->id->capability & 1))
1581                 return -EPERM;
1582         if (HWIF(drive)->ide_dma_check == NULL)
1583                 return -EPERM;
1584         if (arg) {
1585                 if (HWIF(drive)->ide_dma_check(drive)) return -EIO;
1586                 if (HWIF(drive)->ide_dma_on(drive)) return -EIO;
1587         } else {
1588                 if (__ide_dma_off(drive))
1589                         return -EIO;
1590         }
1591         return 0;
1592 #else
1593         return -EPERM;
1594 #endif
1595 }
1596
1597 static int set_pio_mode (ide_drive_t *drive, int arg)
1598 {
1599         struct request rq;
1600
1601         if (!HWIF(drive)->tuneproc)
1602                 return -ENOSYS;
1603         if (drive->special.b.set_tune)
1604                 return -EBUSY;
1605         ide_init_drive_cmd(&rq);
1606         drive->tune_req = (u8) arg;
1607         drive->special.b.set_tune = 1;
1608         (void) ide_do_drive_cmd(drive, &rq, ide_wait);
1609         return 0;
1610 }
1611
1612 static int set_xfer_rate (ide_drive_t *drive, int arg)
1613 {
1614         int err = ide_wait_cmd(drive,
1615                         WIN_SETFEATURES, (u8) arg,
1616                         SETFEATURES_XFER, 0, NULL);
1617
1618         if (!err && arg) {
1619                 ide_set_xfer_rate(drive, (u8) arg);
1620                 ide_driveid_update(drive);
1621         }
1622         return err;
1623 }
1624
1625 /**
1626  *      ide_add_generic_settings        -       generic ide settings
1627  *      @drive: drive being configured
1628  *
1629  *      Add the generic parts of the system settings to the /proc files and
1630  *      ioctls for this IDE device. The caller must not be holding the
1631  *      ide_setting_sem.
1632  */
1633
1634 void ide_add_generic_settings (ide_drive_t *drive)
1635 {
1636         down(&ide_setting_sem);
1637 /*
1638  *                      drive   setting name            read/write access                               read ioctl              write ioctl             data type       min     max                             mul_factor      div_factor      data pointer                    set function
1639  */
1640         ide_add_setting(drive,  "io_32bit",             drive->no_io_32bit ? SETTING_READ : SETTING_RW, HDIO_GET_32BIT,         HDIO_SET_32BIT,         TYPE_BYTE,      0,      1 + (SUPPORT_VLB_SYNC << 1),    1,              1,              &drive->io_32bit,               set_io_32bit);
1641         ide_add_setting(drive,  "keepsettings",         SETTING_RW,                                     HDIO_GET_KEEPSETTINGS,  HDIO_SET_KEEPSETTINGS,  TYPE_BYTE,      0,      1,                              1,              1,              &drive->keep_settings,          NULL);
1642         ide_add_setting(drive,  "nice1",                SETTING_RW,                                     -1,                     -1,                     TYPE_BYTE,      0,      1,                              1,              1,              &drive->nice1,                  NULL);
1643         ide_add_setting(drive,  "pio_mode",             SETTING_WRITE,                                  -1,                     HDIO_SET_PIO_MODE,      TYPE_BYTE,      0,      255,                            1,              1,              NULL,                           set_pio_mode);
1644         ide_add_setting(drive,  "unmaskirq",            drive->no_unmask ? SETTING_READ : SETTING_RW,   HDIO_GET_UNMASKINTR,    HDIO_SET_UNMASKINTR,    TYPE_BYTE,      0,      1,                              1,              1,              &drive->unmask,                 NULL);
1645         ide_add_setting(drive,  "using_dma",            SETTING_RW,                                     HDIO_GET_DMA,           HDIO_SET_DMA,           TYPE_BYTE,      0,      1,                              1,              1,              &drive->using_dma,              set_using_dma);
1646         ide_add_setting(drive,  "init_speed",           SETTING_RW,                                     -1,                     -1,                     TYPE_BYTE,      0,      70,                             1,              1,              &drive->init_speed,             NULL);
1647         ide_add_setting(drive,  "current_speed",        SETTING_RW,                                     -1,                     -1,                     TYPE_BYTE,      0,      70,                             1,              1,              &drive->current_speed,          set_xfer_rate);
1648         ide_add_setting(drive,  "number",               SETTING_RW,                                     -1,                     -1,                     TYPE_BYTE,      0,      3,                              1,              1,              &drive->dn,                     NULL);
1649
1650         up(&ide_setting_sem);
1651 }
1652
1653 /**
1654  *      system_bus_clock        -       clock guess
1655  *
1656  *      External version of the bus clock guess used by very old IDE drivers
1657  *      for things like VLB timings. Should not be used.
1658  */
1659
1660 int system_bus_clock (void)
1661 {
1662         return((int) ((!system_bus_speed) ? ide_system_bus_speed() : system_bus_speed ));
1663 }
1664
1665 EXPORT_SYMBOL(system_bus_clock);
1666
1667 /*
1668  *      Locking is badly broken here - since way back.  That sucker is
1669  * root-only, but that's not an excuse...  The real question is what
1670  * exclusion rules do we want here.
1671  */
1672 int ide_replace_subdriver (ide_drive_t *drive, const char *driver)
1673 {
1674         if (!drive->present || drive->usage || drive->dead)
1675                 goto abort;
1676         if (DRIVER(drive)->cleanup(drive))
1677                 goto abort;
1678         strlcpy(drive->driver_req, driver, sizeof(drive->driver_req));
1679         if (ata_attach(drive)) {
1680                 spin_lock(&drives_lock);
1681                 list_del_init(&drive->list);
1682                 spin_unlock(&drives_lock);
1683                 drive->driver_req[0] = 0;
1684                 ata_attach(drive);
1685         } else {
1686                 drive->driver_req[0] = 0;
1687         }
1688         if (DRIVER(drive)!= &idedefault_driver && !strcmp(DRIVER(drive)->name, driver))
1689                 return 0;
1690 abort:
1691         return 1;
1692 }
1693
1694 /**
1695  *      ata_attach              -       attach an ATA/ATAPI device
1696  *      @drive: drive to attach
1697  *
1698  *      Takes a drive that is as yet not assigned to any midlayer IDE
1699  *      driver (or is assigned to the default driver) and figures out
1700  *      which driver would like to own it. If nobody claims the drive
1701  *      then it is automatically attached to the default driver used for
1702  *      unclaimed objects.
1703  *
1704  *      A return of zero indicates attachment to a driver, of one
1705  *      attachment to the default driver.
1706  *
1707  *      Takes the driver list lock and the ide_settings semaphore.
1708  */
1709
1710 int ata_attach(ide_drive_t *drive)
1711 {
1712         struct list_head *p;
1713         down(&drivers_sem);
1714         down(&ide_setting_sem);
1715         list_for_each(p, &drivers) {
1716                 ide_driver_t *driver = list_entry(p, ide_driver_t, drivers);
1717                 if (!try_module_get(driver->owner))
1718                         continue;
1719                 if (driver->attach(drive) == 0) {
1720                         module_put(driver->owner);
1721                         drive->gendev.driver = &driver->gen_driver;
1722                         up(&ide_setting_sem);
1723                         up(&drivers_sem);
1724                         return 0;
1725                 }
1726                 module_put(driver->owner);
1727         }
1728         drive->gendev.driver = &idedefault_driver.gen_driver;
1729         up(&ide_setting_sem);
1730         up(&drivers_sem);
1731         if(idedefault_driver.attach(drive) != 0)
1732                 panic("ide: default attach failed");
1733         return 1;
1734 }
1735
1736 static int generic_ide_suspend(struct device *dev, u32 state)
1737 {
1738         ide_drive_t *drive = dev->driver_data;
1739         struct request rq;
1740         struct request_pm_state rqpm;
1741         ide_task_t args;
1742
1743         memset(&rq, 0, sizeof(rq));
1744         memset(&rqpm, 0, sizeof(rqpm));
1745         memset(&args, 0, sizeof(args));
1746         rq.flags = REQ_PM_SUSPEND;
1747         rq.special = &args;
1748         rq.pm = &rqpm;
1749         rqpm.pm_step = ide_pm_state_start_suspend;
1750         rqpm.pm_state = state;
1751
1752         return ide_do_drive_cmd(drive, &rq, ide_wait);
1753 }
1754
1755 static int generic_ide_resume(struct device *dev)
1756 {
1757         ide_drive_t *drive = dev->driver_data;
1758         struct request rq;
1759         struct request_pm_state rqpm;
1760         ide_task_t args;
1761
1762         memset(&rq, 0, sizeof(rq));
1763         memset(&rqpm, 0, sizeof(rqpm));
1764         memset(&args, 0, sizeof(args));
1765         rq.flags = REQ_PM_RESUME;
1766         rq.special = &args;
1767         rq.pm = &rqpm;
1768         rqpm.pm_step = ide_pm_state_start_resume;
1769         rqpm.pm_state = 0;
1770
1771         return ide_do_drive_cmd(drive, &rq, ide_head_wait);
1772 }
1773
1774 int generic_ide_ioctl(struct file *file, struct block_device *bdev,
1775                         unsigned int cmd, unsigned long arg)
1776 {
1777         ide_drive_t *drive = bdev->bd_disk->private_data;
1778         ide_settings_t *setting;
1779         int err = 0;
1780         void __user *p = (void __user *)arg;
1781
1782         down(&ide_setting_sem);
1783         if ((setting = ide_find_setting_by_ioctl(drive, cmd)) != NULL) {
1784                 if (cmd == setting->read_ioctl) {
1785                         err = ide_read_setting(drive, setting);
1786                         up(&ide_setting_sem);
1787                         return err >= 0 ? put_user(err, (long __user *)arg) : err;
1788                 } else {
1789                         if (bdev != bdev->bd_contains)
1790                                 err = -EINVAL;
1791                         else
1792                                 err = ide_write_setting(drive, setting, arg);
1793                         up(&ide_setting_sem);
1794                         return err;
1795                 }
1796         }
1797         up(&ide_setting_sem);
1798
1799         switch (cmd) {
1800                 case HDIO_GETGEO:
1801                 {
1802                         struct hd_geometry geom;
1803                         if (!p || (drive->media != ide_disk && drive->media != ide_floppy)) return -EINVAL;
1804                         geom.heads = drive->bios_head;
1805                         geom.sectors = drive->bios_sect;
1806                         geom.cylinders = (u16)drive->bios_cyl; /* truncate */
1807                         geom.start = get_start_sect(bdev);
1808                         if (copy_to_user(p, &geom, sizeof(struct hd_geometry)))
1809                                 return -EFAULT;
1810                         return 0;
1811                 }
1812
1813                 case HDIO_OBSOLETE_IDENTITY:
1814                 case HDIO_GET_IDENTITY:
1815                         if (bdev != bdev->bd_contains)
1816                                 return -EINVAL;
1817                         if (drive->id_read == 0)
1818                                 return -ENOMSG;
1819                         if (copy_to_user(p, drive->id, (cmd == HDIO_GET_IDENTITY) ? sizeof(*drive->id) : 142))
1820                                 return -EFAULT;
1821                         return 0;
1822
1823                 case HDIO_GET_NICE:
1824                         return put_user(drive->dsc_overlap      <<      IDE_NICE_DSC_OVERLAP    |
1825                                         drive->atapi_overlap    <<      IDE_NICE_ATAPI_OVERLAP  |
1826                                         drive->nice0            <<      IDE_NICE_0              |
1827                                         drive->nice1            <<      IDE_NICE_1              |
1828                                         drive->nice2            <<      IDE_NICE_2,
1829                                         (long __user *) arg);
1830
1831 #ifdef CONFIG_IDE_TASK_IOCTL
1832                 case HDIO_DRIVE_TASKFILE:
1833                         if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
1834                                 return -EACCES;
1835                         switch(drive->media) {
1836                                 case ide_disk:
1837                                         return ide_taskfile_ioctl(drive, cmd, arg);
1838                                 default:
1839                                         return -ENOMSG;
1840                         }
1841 #endif /* CONFIG_IDE_TASK_IOCTL */
1842
1843                 case HDIO_DRIVE_CMD:
1844                         if (!capable(CAP_SYS_RAWIO))
1845                                 return -EACCES;
1846                         return ide_cmd_ioctl(drive, cmd, arg);
1847
1848                 case HDIO_DRIVE_TASK:
1849                         if (!capable(CAP_SYS_RAWIO))
1850                                 return -EACCES;
1851                         return ide_task_ioctl(drive, cmd, arg);
1852
1853                 case HDIO_SCAN_HWIF:
1854                 {
1855                         hw_regs_t hw;
1856                         ide_hwif_t *hwif;
1857                         int args[3];
1858                         if (!capable(CAP_SYS_RAWIO)) return -EACCES;
1859                         if (copy_from_user(args, p, 3 * sizeof(int)))
1860                                 return -EFAULT;
1861                         memset(&hw, 0, sizeof(hw));
1862                         ide_init_hwif_ports(&hw, (unsigned long) args[0],
1863                                             (unsigned long) args[1], NULL);
1864                         hw.irq = args[2];
1865                         if (ide_register_hw(&hw, &hwif) == -1)
1866                                 return -EIO;
1867                         hwif->user_dev = 1;
1868                         return 0;
1869                 }
1870                 case HDIO_UNREGISTER_HWIF:
1871                         if (!capable(CAP_SYS_RAWIO)) return -EACCES;
1872                         if(arg > MAX_HWIFS || arg < 0)
1873                                 return -EINVAL;
1874                         if(!ide_hwifs[arg].user_dev)
1875                                 return -EINVAL;
1876                         return ide_unregister_hwif(&ide_hwifs[arg]);
1877                         return 0;
1878                 case HDIO_SET_NICE:
1879                         if (!capable(CAP_SYS_ADMIN)) return -EACCES;
1880                         if (arg != (arg & ((1 << IDE_NICE_DSC_OVERLAP) | (1 << IDE_NICE_1))))
1881                                 return -EPERM;
1882                         drive->dsc_overlap = (arg >> IDE_NICE_DSC_OVERLAP) & 1;
1883                         if (drive->dsc_overlap && !DRIVER(drive)->supports_dsc_overlap) {
1884                                 drive->dsc_overlap = 0;
1885                                 return -EPERM;
1886                         }
1887                         drive->nice1 = (arg >> IDE_NICE_1) & 1;
1888                         return 0;
1889                 case HDIO_DRIVE_RESET:
1890                 {
1891                         unsigned long flags;
1892                         if (!capable(CAP_SYS_ADMIN)) return -EACCES;
1893                         
1894                         /*
1895                          *      Abort the current command on the
1896                          *      group if there is one, taking
1897                          *      care not to allow anything else
1898                          *      to be queued and to die on the
1899                          *      spot if we miss one somehow
1900                          */
1901
1902
1903                         /* FIXME: need to block new commands here, must
1904                            find a better approach! */
1905                         HWGROUP(drive)->busy = 1;
1906                         DRIVER(drive)->abort(drive, "drive reset");
1907                         
1908                         spin_lock_irqsave(&ide_lock, flags);
1909                         if(HWGROUP(drive)->handler)
1910                                 BUG();
1911                                 
1912                         /* Ensure nothing gets queued after we
1913                            drop the lock. Reset will clear the busy */
1914                    
1915                         HWGROUP(drive)->busy = 1;
1916                         spin_unlock_irqrestore(&ide_lock, flags);
1917                         (void) ide_do_reset(drive);
1918                         if (drive->suspend_reset) {
1919 /*
1920  *                              APM WAKE UP todo !!
1921  *                              int nogoodpower = 1;
1922  *                              while(nogoodpower) {
1923  *                                      check_power1() or check_power2()
1924  *                                      nogoodpower = 0;
1925  *                              } 
1926  *                              HWIF(drive)->multiproc(drive);
1927  */
1928                                 return ioctl_by_bdev(bdev, BLKRRPART, 0);
1929                         }
1930                         return 0;
1931                 }
1932
1933                 case CDROMEJECT:
1934                 case CDROMCLOSETRAY:
1935                         return scsi_cmd_ioctl(file, bdev->bd_disk, cmd, p);
1936
1937                 case HDIO_GET_BUSSTATE:
1938                         if (!capable(CAP_SYS_ADMIN))
1939                                 return -EACCES;
1940                         if (put_user(HWIF(drive)->bus_state, (long __user *)arg))
1941                                 return -EFAULT;
1942                         return 0;
1943
1944                 case HDIO_SET_BUSSTATE:
1945                         if (!capable(CAP_SYS_ADMIN))
1946                                 return -EACCES;
1947                         if (HWIF(drive)->busproc)
1948                                 return HWIF(drive)->busproc(drive, (int)arg);
1949                         return -EOPNOTSUPP;
1950                 default:
1951                         return -EINVAL;
1952         }
1953 }
1954
1955 EXPORT_SYMBOL(generic_ide_ioctl);
1956
1957 /*
1958  * stridx() returns the offset of c within s,
1959  * or -1 if c is '\0' or not found within s.
1960  */
1961 static int __init stridx (const char *s, char c)
1962 {
1963         char *i = strchr(s, c);
1964         return (i && c) ? i - s : -1;
1965 }
1966
1967 /*
1968  * match_parm() does parsing for ide_setup():
1969  *
1970  * 1. the first char of s must be '='.
1971  * 2. if the remainder matches one of the supplied keywords,
1972  *     the index (1 based) of the keyword is negated and returned.
1973  * 3. if the remainder is a series of no more than max_vals numbers
1974  *     separated by commas, the numbers are saved in vals[] and a
1975  *     count of how many were saved is returned.  Base10 is assumed,
1976  *     and base16 is allowed when prefixed with "0x".
1977  * 4. otherwise, zero is returned.
1978  */
1979 static int __init match_parm (char *s, const char *keywords[], int vals[], int max_vals)
1980 {
1981         static const char *decimal = "0123456789";
1982         static const char *hex = "0123456789abcdef";
1983         int i, n;
1984
1985         if (*s++ == '=') {
1986                 /*
1987                  * Try matching against the supplied keywords,
1988                  * and return -(index+1) if we match one
1989                  */
1990                 if (keywords != NULL) {
1991                         for (i = 0; *keywords != NULL; ++i) {
1992                                 if (!strcmp(s, *keywords++))
1993                                         return -(i+1);
1994                         }
1995                 }
1996                 /*
1997                  * Look for a series of no more than "max_vals"
1998                  * numeric values separated by commas, in base10,
1999                  * or base16 when prefixed with "0x".
2000                  * Return a count of how many were found.
2001                  */
2002                 for (n = 0; (i = stridx(decimal, *s)) >= 0;) {
2003                         vals[n] = i;
2004                         while ((i = stridx(decimal, *++s)) >= 0)
2005                                 vals[n] = (vals[n] * 10) + i;
2006                         if (*s == 'x' && !vals[n]) {
2007                                 while ((i = stridx(hex, *++s)) >= 0)
2008                                         vals[n] = (vals[n] * 0x10) + i;
2009                         }
2010                         if (++n == max_vals)
2011                                 break;
2012                         if (*s == ',' || *s == ';')
2013                                 ++s;
2014                 }
2015                 if (!*s)
2016                         return n;
2017         }
2018         return 0;       /* zero = nothing matched */
2019 }
2020
2021 #ifdef CONFIG_BLK_DEV_ALI14XX
2022 static int __initdata probe_ali14xx;
2023 extern int ali14xx_init(void);
2024 #endif
2025 #ifdef CONFIG_BLK_DEV_UMC8672
2026 static int __initdata probe_umc8672;
2027 extern int umc8672_init(void);
2028 #endif
2029 #ifdef CONFIG_BLK_DEV_DTC2278
2030 static int __initdata probe_dtc2278;
2031 extern int dtc2278_init(void);
2032 #endif
2033 #ifdef CONFIG_BLK_DEV_HT6560B
2034 static int __initdata probe_ht6560b;
2035 extern int ht6560b_init(void);
2036 #endif
2037 #ifdef CONFIG_BLK_DEV_QD65XX
2038 static int __initdata probe_qd65xx;
2039 extern int qd65xx_init(void);
2040 #endif
2041
2042 static int __initdata is_chipset_set[MAX_HWIFS];
2043
2044 /*
2045  * ide_setup() gets called VERY EARLY during initialization,
2046  * to handle kernel "command line" strings beginning with "hdx=" or "ide".
2047  *
2048  * Remember to update Documentation/ide.txt if you change something here.
2049  */
2050 int __init ide_setup (char *s)
2051 {
2052         int i, vals[3];
2053         ide_hwif_t *hwif;
2054         ide_drive_t *drive;
2055         unsigned int hw, unit;
2056         const char max_drive = 'a' + ((MAX_HWIFS * MAX_DRIVES) - 1);
2057         const char max_hwif  = '0' + (MAX_HWIFS - 1);
2058
2059         
2060         if (strncmp(s,"hd",2) == 0 && s[2] == '=')      /* hd= is for hd.c   */
2061                 return 0;                               /* driver and not us */
2062
2063         if (strncmp(s,"ide",3) && strncmp(s,"idebus",6) && strncmp(s,"hd",2))
2064                 return 0;
2065
2066         printk(KERN_INFO "ide_setup: %s", s);
2067         init_ide_data ();
2068
2069 #ifdef CONFIG_BLK_DEV_IDEDOUBLER
2070         if (!strcmp(s, "ide=doubler")) {
2071                 extern int ide_doubler;
2072
2073                 printk(" : Enabled support for IDE doublers\n");
2074                 ide_doubler = 1;
2075                 return 1;
2076         }
2077 #endif /* CONFIG_BLK_DEV_IDEDOUBLER */
2078
2079         if (!strcmp(s, "ide=nodma")) {
2080                 printk(" : Prevented DMA\n");
2081                 noautodma = 1;
2082                 return 1;
2083         }
2084
2085 #ifdef CONFIG_BLK_DEV_IDEPCI
2086         if (!strcmp(s, "ide=reverse")) {
2087                 ide_scan_direction = 1;
2088                 printk(" : Enabled support for IDE inverse scan order.\n");
2089                 return 1;
2090         }
2091 #endif /* CONFIG_BLK_DEV_IDEPCI */
2092
2093         /*
2094          * Look for drive options:  "hdx="
2095          */
2096         if (s[0] == 'h' && s[1] == 'd' && s[2] >= 'a' && s[2] <= max_drive) {
2097                 const char *hd_words[] = {
2098                         "none", "noprobe", "nowerr", "cdrom", "serialize",
2099                         "autotune", "noautotune", "minus8", "swapdata", "bswap",
2100                         "minus11", "remap", "remap63", "scsi", NULL };
2101                 unit = s[2] - 'a';
2102                 hw   = unit / MAX_DRIVES;
2103                 unit = unit % MAX_DRIVES;
2104                 hwif = &ide_hwifs[hw];
2105                 drive = &hwif->drives[unit];
2106                 if (strncmp(s + 4, "ide-", 4) == 0) {
2107                         strlcpy(drive->driver_req, s + 4, sizeof(drive->driver_req));
2108                         goto done;
2109                 }
2110                 switch (match_parm(&s[3], hd_words, vals, 3)) {
2111                         case -1: /* "none" */
2112                         case -2: /* "noprobe" */
2113                                 drive->noprobe = 1;
2114                                 goto done;
2115                         case -3: /* "nowerr" */
2116                                 drive->bad_wstat = BAD_R_STAT;
2117                                 hwif->noprobe = 0;
2118                                 goto done;
2119                         case -4: /* "cdrom" */
2120                                 drive->present = 1;
2121                                 drive->media = ide_cdrom;
2122                                 hwif->noprobe = 0;
2123                                 goto done;
2124                         case -5: /* "serialize" */
2125                                 printk(" -- USE \"ide%d=serialize\" INSTEAD", hw);
2126                                 goto do_serialize;
2127                         case -6: /* "autotune" */
2128                                 drive->autotune = IDE_TUNE_AUTO;
2129                                 goto done;
2130                         case -7: /* "noautotune" */
2131                                 drive->autotune = IDE_TUNE_NOAUTO;
2132                                 goto done;
2133                         case -9: /* "swapdata" */
2134                         case -10: /* "bswap" */
2135                                 drive->bswap = 1;
2136                                 goto done;
2137                         case -12: /* "remap" */
2138                                 drive->remap_0_to_1 = 1;
2139                                 goto done;
2140                         case -13: /* "remap63" */
2141                                 drive->sect0 = 63;
2142                                 goto done;
2143                         case -14: /* "scsi" */
2144                                 drive->scsi = 1;
2145                                 goto done;
2146                         case 3: /* cyl,head,sect */
2147                                 drive->media    = ide_disk;
2148                                 drive->cyl      = drive->bios_cyl  = vals[0];
2149                                 drive->head     = drive->bios_head = vals[1];
2150                                 drive->sect     = drive->bios_sect = vals[2];
2151                                 drive->present  = 1;
2152                                 drive->forced_geom = 1;
2153                                 hwif->noprobe = 0;
2154                                 goto done;
2155                         default:
2156                                 goto bad_option;
2157                 }
2158         }
2159
2160         if (s[0] != 'i' || s[1] != 'd' || s[2] != 'e')
2161                 goto bad_option;
2162         /*
2163          * Look for bus speed option:  "idebus="
2164          */
2165         if (s[3] == 'b' && s[4] == 'u' && s[5] == 's') {
2166                 if (match_parm(&s[6], NULL, vals, 1) != 1)
2167                         goto bad_option;
2168                 if (vals[0] >= 20 && vals[0] <= 66) {
2169                         idebus_parameter = vals[0];
2170                 } else
2171                         printk(" -- BAD BUS SPEED! Expected value from 20 to 66");
2172                 goto done;
2173         }
2174         /*
2175          * Look for interface options:  "idex="
2176          */
2177         if (s[3] >= '0' && s[3] <= max_hwif) {
2178                 /*
2179                  * Be VERY CAREFUL changing this: note hardcoded indexes below
2180                  * (-8, -9, -10) are reserved to ease the hardcoding.
2181                  */
2182                 static const char *ide_words[] = {
2183                         "noprobe", "serialize", "autotune", "noautotune", 
2184                         "reset", "dma", "ata66", "minus8", "minus9",
2185                         "minus10", "four", "qd65xx", "ht6560b", "cmd640_vlb",
2186                         "dtc2278", "umc8672", "ali14xx", NULL };
2187                 hw = s[3] - '0';
2188                 hwif = &ide_hwifs[hw];
2189                 i = match_parm(&s[4], ide_words, vals, 3);
2190
2191                 /*
2192                  * Cryptic check to ensure chipset not already set for hwif.
2193                  * Note: we can't depend on hwif->chipset here.
2194                  */
2195                 if ((i >= -18 && i <= -11) || (i > 0 && i <= 3)) {
2196                         /* chipset already specified */
2197                         if (is_chipset_set[hw])
2198                                 goto bad_option;
2199                         if (i > -18 && i <= -11) {
2200                                 /* these drivers are for "ide0=" only */
2201                                 if (hw != 0)
2202                                         goto bad_hwif;
2203                                 /* chipset already specified for 2nd port */
2204                                 if (is_chipset_set[hw+1])
2205                                         goto bad_option;
2206                         }
2207                         is_chipset_set[hw] = 1;
2208                         printk("\n");
2209                 }
2210
2211                 switch (i) {
2212 #ifdef CONFIG_BLK_DEV_ALI14XX
2213                         case -17: /* "ali14xx" */
2214                                 probe_ali14xx = 1;
2215                                 goto done;
2216 #endif
2217 #ifdef CONFIG_BLK_DEV_UMC8672
2218                         case -16: /* "umc8672" */
2219                                 probe_umc8672 = 1;
2220                                 goto done;
2221 #endif
2222 #ifdef CONFIG_BLK_DEV_DTC2278
2223                         case -15: /* "dtc2278" */
2224                                 probe_dtc2278 = 1;
2225                                 goto done;
2226 #endif
2227 #ifdef CONFIG_BLK_DEV_CMD640
2228                         case -14: /* "cmd640_vlb" */
2229                         {
2230                                 extern int cmd640_vlb; /* flag for cmd640.c */
2231                                 cmd640_vlb = 1;
2232                                 goto done;
2233                         }
2234 #endif
2235 #ifdef CONFIG_BLK_DEV_HT6560B
2236                         case -13: /* "ht6560b" */
2237                                 probe_ht6560b = 1;
2238                                 goto done;
2239 #endif
2240 #ifdef CONFIG_BLK_DEV_QD65XX
2241                         case -12: /* "qd65xx" */
2242                                 probe_qd65xx = 1;
2243                                 goto done;
2244 #endif
2245 #ifdef CONFIG_BLK_DEV_4DRIVES
2246                         case -11: /* "four" drives on one set of ports */
2247                         {
2248                                 ide_hwif_t *mate = &ide_hwifs[hw^1];
2249                                 mate->drives[0].select.all ^= 0x20;
2250                                 mate->drives[1].select.all ^= 0x20;
2251                                 hwif->chipset = mate->chipset = ide_4drives;
2252                                 mate->irq = hwif->irq;
2253                                 memcpy(mate->io_ports, hwif->io_ports, sizeof(hwif->io_ports));
2254                                 goto do_serialize;
2255                         }
2256 #endif /* CONFIG_BLK_DEV_4DRIVES */
2257                         case -10: /* minus10 */
2258                         case -9: /* minus9 */
2259                         case -8: /* minus8 */
2260                                 goto bad_option;
2261                         case -7: /* ata66 */
2262 #ifdef CONFIG_BLK_DEV_IDEPCI
2263                                 hwif->udma_four = 1;
2264                                 goto done;
2265 #else
2266                                 goto bad_hwif;
2267 #endif
2268                         case -6: /* dma */
2269                                 hwif->autodma = 1;
2270                                 goto done;
2271                         case -5: /* "reset" */
2272                                 hwif->reset = 1;
2273                                 goto done;
2274                         case -4: /* "noautotune" */
2275                                 hwif->drives[0].autotune = IDE_TUNE_NOAUTO;
2276                                 hwif->drives[1].autotune = IDE_TUNE_NOAUTO;
2277                                 goto done;
2278                         case -3: /* "autotune" */
2279                                 hwif->drives[0].autotune = IDE_TUNE_AUTO;
2280                                 hwif->drives[1].autotune = IDE_TUNE_AUTO;
2281                                 goto done;
2282                         case -2: /* "serialize" */
2283                         do_serialize:
2284                                 hwif->mate = &ide_hwifs[hw^1];
2285                                 hwif->mate->mate = hwif;
2286                                 hwif->serialized = hwif->mate->serialized = 1;
2287                                 goto done;
2288
2289                         case -1: /* "noprobe" */
2290                                 hwif->noprobe = 1;
2291                                 goto done;
2292
2293                         case 1: /* base */
2294                                 vals[1] = vals[0] + 0x206; /* default ctl */
2295                         case 2: /* base,ctl */
2296                                 vals[2] = 0;    /* default irq = probe for it */
2297                         case 3: /* base,ctl,irq */
2298                                 hwif->hw.irq = vals[2];
2299                                 ide_init_hwif_ports(&hwif->hw, (unsigned long) vals[0], (unsigned long) vals[1], &hwif->irq);
2300                                 memcpy(hwif->io_ports, hwif->hw.io_ports, sizeof(hwif->io_ports));
2301                                 hwif->irq      = vals[2];
2302                                 hwif->noprobe  = 0;
2303                                 hwif->chipset  = ide_forced;
2304                                 goto done;
2305
2306                         case 0: goto bad_option;
2307                         default:
2308                                 printk(" -- SUPPORT NOT CONFIGURED IN THIS KERNEL\n");
2309                                 return 1;
2310                 }
2311         }
2312 bad_option:
2313         printk(" -- BAD OPTION\n");
2314         return 1;
2315 bad_hwif:
2316         printk("-- NOT SUPPORTED ON ide%d", hw);
2317 done:
2318         printk("\n");
2319         return 1;
2320 }
2321
2322 extern void pnpide_init(void);
2323 extern void h8300_ide_init(void);
2324
2325 /*
2326  * probe_for_hwifs() finds/initializes "known" IDE interfaces
2327  */
2328 static void __init probe_for_hwifs (void)
2329 {
2330 #ifdef CONFIG_BLK_DEV_IDEPCI
2331         ide_scan_pcibus(ide_scan_direction);
2332 #endif /* CONFIG_BLK_DEV_IDEPCI */
2333
2334 #ifdef CONFIG_ETRAX_IDE
2335         {
2336                 extern void init_e100_ide(void);
2337                 init_e100_ide();
2338         }
2339 #endif /* CONFIG_ETRAX_IDE */
2340 #ifdef CONFIG_BLK_DEV_CMD640
2341         {
2342                 extern void ide_probe_for_cmd640x(void);
2343                 ide_probe_for_cmd640x();
2344         }
2345 #endif /* CONFIG_BLK_DEV_CMD640 */
2346 #ifdef CONFIG_BLK_DEV_IDE_PMAC
2347         {
2348                 extern void pmac_ide_probe(void);
2349                 pmac_ide_probe();
2350         }
2351 #endif /* CONFIG_BLK_DEV_IDE_PMAC */
2352 #ifdef CONFIG_BLK_DEV_GAYLE
2353         {
2354                 extern void gayle_init(void);
2355                 gayle_init();
2356         }
2357 #endif /* CONFIG_BLK_DEV_GAYLE */
2358 #ifdef CONFIG_BLK_DEV_FALCON_IDE
2359         {
2360                 extern void falconide_init(void);
2361                 falconide_init();
2362         }
2363 #endif /* CONFIG_BLK_DEV_FALCON_IDE */
2364 #ifdef CONFIG_BLK_DEV_MAC_IDE
2365         {
2366                 extern void macide_init(void);
2367                 macide_init();
2368         }
2369 #endif /* CONFIG_BLK_DEV_MAC_IDE */
2370 #ifdef CONFIG_BLK_DEV_Q40IDE
2371         {
2372                 extern void q40ide_init(void);
2373                 q40ide_init();
2374         }
2375 #endif /* CONFIG_BLK_DEV_Q40IDE */
2376 #ifdef CONFIG_BLK_DEV_BUDDHA
2377         {
2378                 extern void buddha_init(void);
2379                 buddha_init();
2380         }
2381 #endif /* CONFIG_BLK_DEV_BUDDHA */
2382 #ifdef CONFIG_BLK_DEV_IDEPNP
2383         pnpide_init();
2384 #endif
2385 #ifdef CONFIG_H8300
2386         h8300_ide_init();
2387 #endif
2388 }
2389
2390 /*
2391  *      Actually unregister the subdriver. Called with the
2392  *      request lock dropped.
2393  */
2394  
2395 static int default_cleanup (ide_drive_t *drive)
2396 {
2397         return ide_unregister_subdriver(drive);
2398 }
2399
2400 static ide_startstop_t default_do_request (ide_drive_t *drive, struct request *rq, sector_t block)
2401 {
2402         ide_end_request(drive, 0, 0);
2403         return ide_stopped;
2404 }
2405
2406 static int default_end_request (ide_drive_t *drive, int uptodate, int nr_sects)
2407 {
2408         return ide_end_request(drive, uptodate, nr_sects);
2409 }
2410
2411 static u8 default_sense (ide_drive_t *drive, const char *msg, u8 stat)
2412 {
2413         return ide_dump_status(drive, msg, stat);
2414 }
2415
2416 static ide_startstop_t default_error (ide_drive_t *drive, const char *msg, u8 stat)
2417 {
2418         return ide_error(drive, msg, stat);
2419 }
2420
2421 static void default_pre_reset (ide_drive_t *drive)
2422 {
2423 }
2424
2425 static sector_t default_capacity (ide_drive_t *drive)
2426 {
2427         return 0x7fffffff;
2428 }
2429
2430 static ide_startstop_t default_special (ide_drive_t *drive)
2431 {
2432         special_t *s = &drive->special;
2433
2434         s->all = 0;
2435         drive->mult_req = 0;
2436         return ide_stopped;
2437 }
2438
2439 static int default_attach (ide_drive_t *drive)
2440 {
2441         printk(KERN_ERR "%s: does not support hotswap of device class !\n",
2442                 drive->name);
2443
2444         return 0;
2445 }
2446
2447 static ide_startstop_t default_abort (ide_drive_t *drive, const char *msg)
2448 {
2449         return ide_abort(drive, msg);
2450 }
2451
2452 static ide_startstop_t default_start_power_step(ide_drive_t *drive,
2453                                                 struct request *rq)
2454 {
2455         rq->pm->pm_step = ide_pm_state_completed;
2456         return ide_stopped;
2457 }
2458
2459 static void setup_driver_defaults (ide_driver_t *d)
2460 {
2461         if (d->cleanup == NULL)         d->cleanup = default_cleanup;
2462         if (d->do_request == NULL)      d->do_request = default_do_request;
2463         if (d->end_request == NULL)     d->end_request = default_end_request;
2464         if (d->sense == NULL)           d->sense = default_sense;
2465         if (d->error == NULL)           d->error = default_error;
2466         if (d->abort == NULL)           d->abort = default_abort;
2467         if (d->pre_reset == NULL)       d->pre_reset = default_pre_reset;
2468         if (d->capacity == NULL)        d->capacity = default_capacity;
2469         if (d->special == NULL)         d->special = default_special;
2470         if (d->attach == NULL)          d->attach = default_attach;
2471         if (d->start_power_step == NULL)
2472                 d->start_power_step = default_start_power_step;
2473 }
2474
2475 int ide_register_subdriver(ide_drive_t *drive, ide_driver_t *driver)
2476 {
2477         unsigned long flags;
2478
2479         BUG_ON(!drive->driver);
2480
2481         spin_lock_irqsave(&ide_lock, flags);
2482         if (!drive->present || drive->driver != &idedefault_driver ||
2483             drive->usage || drive->dead) {
2484                 spin_unlock_irqrestore(&ide_lock, flags);
2485                 return 1;
2486         }
2487         drive->driver = driver;
2488         spin_unlock_irqrestore(&ide_lock, flags);
2489         spin_lock(&drives_lock);
2490         list_add_tail(&drive->list, &driver->drives);
2491         spin_unlock(&drives_lock);
2492 //      printk(KERN_INFO "%s: attached %s driver.\n", drive->name, driver->name);
2493         if ((drive->autotune == IDE_TUNE_DEFAULT) ||
2494                 (drive->autotune == IDE_TUNE_AUTO)) {
2495                 /* DMA timings and setup moved to ide-probe.c */
2496                 drive->dsc_overlap = (drive->next != drive && driver->supports_dsc_overlap);
2497                 drive->nice1 = 1;
2498         }
2499         drive->suspend_reset = 0;
2500 #ifdef CONFIG_PROC_FS
2501         if (drive->driver != &idedefault_driver) {
2502                 ide_add_proc_entries(drive->proc, generic_subdriver_entries, ide_drive_to_key(drive));
2503                 ide_add_proc_entries(drive->proc, driver->proc, ide_drive_to_key(drive));
2504         }
2505 #endif
2506         return 0;
2507 }
2508
2509 EXPORT_SYMBOL(ide_register_subdriver);
2510
2511 /**
2512  *      ide_unregister_subdriver        -       disconnect drive from driver
2513  *      @drive: drive to unplug
2514  *
2515  *      Disconnect a drive from the driver it was attached to and then
2516  *      clean up the various proc files and other objects attached to it.
2517  *
2518  *      Takes ide_setting_sem, ide_lock and drives_lock.
2519  *      Caller must hold none of the locks.
2520  *
2521  *      No locking versus subdriver unload because we are moving to the
2522  *      default driver anyway. Wants double checking.
2523  */
2524
2525 int ide_unregister_subdriver (ide_drive_t *drive)
2526 {
2527         unsigned long flags;
2528         ide_proc_entry_t *dir;
2529         
2530         down(&ide_setting_sem);
2531         spin_lock_irqsave(&ide_lock, flags);
2532         if (drive->usage || drive->driver == &idedefault_driver || DRIVER(drive)->busy) {
2533                 spin_unlock_irqrestore(&ide_lock, flags);
2534                 up(&ide_setting_sem);
2535                 return 1;
2536         }
2537         dir = DRIVER(drive)->proc;
2538         drive->driver = &idedefault_driver;
2539         spin_unlock_irqrestore(&ide_lock, flags);
2540 #ifdef CONFIG_PROC_FS
2541         ide_remove_proc_entries(drive->proc, dir);
2542         ide_remove_proc_entries(drive->proc, generic_subdriver_entries);
2543 #endif
2544         auto_remove_settings(drive);
2545         up(&ide_setting_sem);
2546         spin_lock(&drives_lock);
2547         list_del_init(&drive->list);
2548         spin_unlock(&drives_lock);
2549         /* drive will be added to &idedefault_driver->drives in ata_attach() */
2550         return 0;
2551 }
2552
2553 EXPORT_SYMBOL(ide_unregister_subdriver);
2554
2555 static int ide_drive_remove(struct device * dev)
2556 {
2557         ide_drive_t * drive = container_of(dev,ide_drive_t,gendev);
2558         DRIVER(drive)->cleanup(drive);
2559         return 0;
2560 }
2561
2562 /**
2563  *      ide_register_driver     -       register IDE device driver
2564  *      @driver: the IDE device driver
2565  *
2566  *      Register a new device driver and then scan the devices
2567  *      on the IDE bus in case any should be attached to the
2568  *      driver we have just registered.  If so attach them.
2569  *
2570  *      Takes the drivers and drives lock. Should take the
2571  *      ide_sem but doesn't - FIXME ??
2572  */
2573
2574 int ide_register_driver(ide_driver_t *driver)
2575 {
2576         struct list_head list;
2577         struct list_head *list_loop;
2578         struct list_head *tmp_storage;
2579
2580         setup_driver_defaults(driver);
2581
2582         down(&drivers_sem);
2583         spin_lock(&drivers_lock);
2584         list_add(&driver->drivers, &drivers);
2585         spin_unlock(&drivers_lock);
2586         up(&drivers_sem);
2587
2588         INIT_LIST_HEAD(&list);
2589         spin_lock(&drives_lock);
2590         list_splice_init(&idedefault_driver.drives, &list);
2591         spin_unlock(&drives_lock);
2592
2593         list_for_each_safe(list_loop, tmp_storage, &list) {
2594                 ide_drive_t *drive = container_of(list_loop, ide_drive_t, list);
2595                 list_del_init(&drive->list);
2596                 if (drive->present)
2597                         ata_attach(drive);
2598         }
2599         driver->gen_driver.name = (char *) driver->name;
2600         driver->gen_driver.bus = &ide_bus_type;
2601         driver->gen_driver.remove = ide_drive_remove;
2602         return driver_register(&driver->gen_driver);
2603 }
2604
2605 EXPORT_SYMBOL(ide_register_driver);
2606
2607 /**
2608  *      ide_unregister_driver   -       unregister IDE device driver
2609  *      @driver: the IDE device driver
2610  *
2611  *      Called when a driver module is being unloaded. We reattach any
2612  *      devices to whatever driver claims them next (typically the default
2613  *      driver).
2614  *
2615  *      Takes drivers_lock and called functions will take ide_setting_sem.
2616  */
2617
2618 void ide_unregister_driver(ide_driver_t *driver)
2619 {
2620         ide_drive_t *drive;
2621
2622         down(&drivers_sem);
2623         spin_lock(&drivers_lock);
2624         list_del(&driver->drivers);
2625         spin_unlock(&drivers_lock);
2626         up(&drivers_sem);
2627
2628         driver_unregister(&driver->gen_driver);
2629
2630         while(!list_empty(&driver->drives)) {
2631                 drive = list_entry(driver->drives.next, ide_drive_t, list);
2632                 if (driver->cleanup(drive)) {
2633                         printk(KERN_ERR "%s: cleanup_module() called while still busy\n", drive->name);
2634                         BUG();
2635                 }
2636                 ata_attach(drive);
2637         }
2638 }
2639
2640 EXPORT_SYMBOL(ide_unregister_driver);
2641
2642 struct block_device_operations ide_fops[] = {{
2643         .owner          = THIS_MODULE,
2644         .open           = ide_open,
2645 }};
2646
2647 EXPORT_SYMBOL(ide_fops);
2648
2649 /*
2650  * Probe module
2651  */
2652
2653 EXPORT_SYMBOL(ide_lock);
2654
2655 struct bus_type ide_bus_type = {
2656         .name           = "ide",
2657         .suspend        = generic_ide_suspend,
2658         .resume         = generic_ide_resume,
2659 };
2660
2661 /*
2662  * This is gets invoked once during initialization, to set *everything* up
2663  */
2664 int __init ide_init (void)
2665 {
2666         printk(KERN_INFO "Uniform Multi-Platform E-IDE driver " REVISION "\n");
2667         devfs_mk_dir("ide");
2668         system_bus_speed = ide_system_bus_speed();
2669
2670         bus_register(&ide_bus_type);
2671
2672         init_ide_data();
2673
2674 #ifdef CONFIG_PROC_FS
2675         proc_ide_root = proc_mkdir("ide", NULL);
2676 #endif
2677
2678 #ifdef CONFIG_BLK_DEV_ALI14XX
2679         if (probe_ali14xx)
2680                 (void)ali14xx_init();
2681 #endif
2682 #ifdef CONFIG_BLK_DEV_UMC8672
2683         if (probe_umc8672)
2684                 (void)umc8672_init();
2685 #endif
2686 #ifdef CONFIG_BLK_DEV_DTC2278
2687         if (probe_dtc2278)
2688                 (void)dtc2278_init();
2689 #endif
2690 #ifdef CONFIG_BLK_DEV_HT6560B
2691         if (probe_ht6560b)
2692                 (void)ht6560b_init();
2693 #endif
2694 #ifdef CONFIG_BLK_DEV_QD65XX
2695         if (probe_qd65xx)
2696                 (void)qd65xx_init();
2697 #endif
2698
2699         initializing = 1;
2700         /* Probe for special PCI and other "known" interface chipsets. */
2701         probe_for_hwifs();
2702         initializing = 0;
2703
2704 #ifdef CONFIG_PROC_FS
2705         proc_ide_create();
2706 #endif
2707         return 0;
2708 }
2709
2710 #ifdef MODULE
2711 char *options = NULL;
2712 module_param(options, charp, 0);
2713 MODULE_LICENSE("GPL");
2714
2715 static void __init parse_options (char *line)
2716 {
2717         char *next = line;
2718
2719         if (line == NULL || !*line)
2720                 return;
2721         while ((line = next) != NULL) {
2722                 if ((next = strchr(line,' ')) != NULL)
2723                         *next++ = 0;
2724                 if (!ide_setup(line))
2725                         printk (KERN_INFO "Unknown option '%s'\n", line);
2726         }
2727 }
2728
2729 int init_module (void)
2730 {
2731         parse_options(options);
2732         return ide_init();
2733 }
2734
2735 void cleanup_module (void)
2736 {
2737         int index;
2738
2739         for (index = 0; index < MAX_HWIFS; ++index) {
2740                 if(ide_unregister_hwif(&ide_hwifs[index]))
2741                         printk(KERN_ERR "ide: unload yet busy!\n");
2742                 if (ide_hwifs[index].dma_base)
2743                         (void) ide_release_dma(&ide_hwifs[index]);
2744         }
2745
2746 #ifdef CONFIG_PROC_FS
2747         proc_ide_destroy();
2748 #endif
2749         devfs_remove("ide");
2750
2751         bus_unregister(&ide_bus_type);
2752 }
2753
2754 #else /* !MODULE */
2755
2756 __setup("", ide_setup);
2757
2758 module_init(ide_init);
2759
2760 #endif /* MODULE */