b9ba7901f716a8c4b82411afd4499a9f602c34e0
[pandora-kernel.git] / drivers / ide / ide-tape.c
1 /*
2  * IDE ATAPI streaming tape driver.
3  *
4  * Copyright (C) 1995-1999  Gadi Oxman <gadio@netvision.net.il>
5  * Copyright (C) 2003-2005  Bartlomiej Zolnierkiewicz
6  *
7  * This driver was constructed as a student project in the software laboratory
8  * of the faculty of electrical engineering in the Technion - Israel's
9  * Institute Of Technology, with the guide of Avner Lottem and Dr. Ilana David.
10  *
11  * It is hereby placed under the terms of the GNU general public license.
12  * (See linux/COPYING).
13  *
14  * For a historical changelog see
15  * Documentation/ide/ChangeLog.ide-tape.1995-2002
16  */
17
18 #define IDETAPE_VERSION "1.19"
19
20 #include <linux/module.h>
21 #include <linux/types.h>
22 #include <linux/string.h>
23 #include <linux/kernel.h>
24 #include <linux/delay.h>
25 #include <linux/timer.h>
26 #include <linux/mm.h>
27 #include <linux/interrupt.h>
28 #include <linux/jiffies.h>
29 #include <linux/major.h>
30 #include <linux/errno.h>
31 #include <linux/genhd.h>
32 #include <linux/slab.h>
33 #include <linux/pci.h>
34 #include <linux/ide.h>
35 #include <linux/smp_lock.h>
36 #include <linux/completion.h>
37 #include <linux/bitops.h>
38 #include <linux/mutex.h>
39
40 #include <asm/byteorder.h>
41 #include <asm/irq.h>
42 #include <asm/uaccess.h>
43 #include <asm/io.h>
44 #include <asm/unaligned.h>
45
46 /*
47  * partition
48  */
49 typedef struct os_partition_s {
50         __u8    partition_num;
51         __u8    par_desc_ver;
52         __u16   wrt_pass_cntr;
53         __u32   first_frame_addr;
54         __u32   last_frame_addr;
55         __u32   eod_frame_addr;
56 } os_partition_t;
57
58 /*
59  * DAT entry
60  */
61 typedef struct os_dat_entry_s {
62         __u32   blk_sz;
63         __u16   blk_cnt;
64         __u8    flags;
65         __u8    reserved;
66 } os_dat_entry_t;
67
68 /*
69  * DAT
70  */
71 #define OS_DAT_FLAGS_DATA       (0xc)
72 #define OS_DAT_FLAGS_MARK       (0x1)
73
74 typedef struct os_dat_s {
75         __u8            dat_sz;
76         __u8            reserved1;
77         __u8            entry_cnt;
78         __u8            reserved3;
79         os_dat_entry_t  dat_list[16];
80 } os_dat_t;
81
82 #include <linux/mtio.h>
83
84 /**************************** Tunable parameters *****************************/
85
86
87 /*
88  *      Pipelined mode parameters.
89  *
90  *      We try to use the minimum number of stages which is enough to
91  *      keep the tape constantly streaming. To accomplish that, we implement
92  *      a feedback loop around the maximum number of stages:
93  *
94  *      We start from MIN maximum stages (we will not even use MIN stages
95  *      if we don't need them), increment it by RATE*(MAX-MIN)
96  *      whenever we sense that the pipeline is empty, until we reach
97  *      the optimum value or until we reach MAX.
98  *
99  *      Setting the following parameter to 0 is illegal: the pipelined mode
100  *      cannot be disabled (calculate_speeds() divides by tape->max_stages.)
101  */
102 #define IDETAPE_MIN_PIPELINE_STAGES       1
103 #define IDETAPE_MAX_PIPELINE_STAGES     400
104 #define IDETAPE_INCREASE_STAGES_RATE     20
105
106 /*
107  *      The following are used to debug the driver:
108  *
109  *      Setting IDETAPE_DEBUG_LOG to 1 will log driver flow control.
110  *
111  *      Setting them to 0 will restore normal operation mode:
112  *
113  *              1.      Disable logging normal successful operations.
114  *              2.      Disable self-sanity checks.
115  *              3.      Errors will still be logged, of course.
116  *
117  *      All the #if DEBUG code will be removed some day, when the driver
118  *      is verified to be stable enough. This will make it much more
119  *      esthetic.
120  */
121 #define IDETAPE_DEBUG_LOG               0
122
123 /*
124  *      After each failed packet command we issue a request sense command
125  *      and retry the packet command IDETAPE_MAX_PC_RETRIES times.
126  *
127  *      Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
128  */
129 #define IDETAPE_MAX_PC_RETRIES          3
130
131 /*
132  *      With each packet command, we allocate a buffer of
133  *      IDETAPE_PC_BUFFER_SIZE bytes. This is used for several packet
134  *      commands (Not for READ/WRITE commands).
135  */
136 #define IDETAPE_PC_BUFFER_SIZE          256
137
138 /*
139  *      In various places in the driver, we need to allocate storage
140  *      for packet commands and requests, which will remain valid while
141  *      we leave the driver to wait for an interrupt or a timeout event.
142  */
143 #define IDETAPE_PC_STACK                (10 + IDETAPE_MAX_PC_RETRIES)
144
145 /*
146  * Some drives (for example, Seagate STT3401A Travan) require a very long
147  * timeout, because they don't return an interrupt or clear their busy bit
148  * until after the command completes (even retension commands).
149  */
150 #define IDETAPE_WAIT_CMD                (900*HZ)
151
152 /*
153  *      The following parameter is used to select the point in the internal
154  *      tape fifo in which we will start to refill the buffer. Decreasing
155  *      the following parameter will improve the system's latency and
156  *      interactive response, while using a high value might improve system
157  *      throughput.
158  */
159 #define IDETAPE_FIFO_THRESHOLD          2
160
161 /*
162  *      DSC polling parameters.
163  *
164  *      Polling for DSC (a single bit in the status register) is a very
165  *      important function in ide-tape. There are two cases in which we
166  *      poll for DSC:
167  *
168  *      1.      Before a read/write packet command, to ensure that we
169  *              can transfer data from/to the tape's data buffers, without
170  *              causing an actual media access. In case the tape is not
171  *              ready yet, we take out our request from the device
172  *              request queue, so that ide.c will service requests from
173  *              the other device on the same interface meanwhile.
174  *
175  *      2.      After the successful initialization of a "media access
176  *              packet command", which is a command which can take a long
177  *              time to complete (it can be several seconds or even an hour).
178  *
179  *              Again, we postpone our request in the middle to free the bus
180  *              for the other device. The polling frequency here should be
181  *              lower than the read/write frequency since those media access
182  *              commands are slow. We start from a "fast" frequency -
183  *              IDETAPE_DSC_MA_FAST (one second), and if we don't receive DSC
184  *              after IDETAPE_DSC_MA_THRESHOLD (5 minutes), we switch it to a
185  *              lower frequency - IDETAPE_DSC_MA_SLOW (1 minute).
186  *
187  *      We also set a timeout for the timer, in case something goes wrong.
188  *      The timeout should be longer then the maximum execution time of a
189  *      tape operation.
190  */
191  
192 /*
193  *      DSC timings.
194  */
195 #define IDETAPE_DSC_RW_MIN              5*HZ/100        /* 50 msec */
196 #define IDETAPE_DSC_RW_MAX              40*HZ/100       /* 400 msec */
197 #define IDETAPE_DSC_RW_TIMEOUT          2*60*HZ         /* 2 minutes */
198 #define IDETAPE_DSC_MA_FAST             2*HZ            /* 2 seconds */
199 #define IDETAPE_DSC_MA_THRESHOLD        5*60*HZ         /* 5 minutes */
200 #define IDETAPE_DSC_MA_SLOW             30*HZ           /* 30 seconds */
201 #define IDETAPE_DSC_MA_TIMEOUT          2*60*60*HZ      /* 2 hours */
202
203 /*************************** End of tunable parameters ***********************/
204
205 /*
206  *      Read/Write error simulation
207  */
208 #define SIMULATE_ERRORS                 0
209
210 /*
211  *      For general magnetic tape device compatibility.
212  */
213 typedef enum {
214         idetape_direction_none,
215         idetape_direction_read,
216         idetape_direction_write
217 } idetape_chrdev_direction_t;
218
219 struct idetape_bh {
220         u32 b_size;
221         atomic_t b_count;
222         struct idetape_bh *b_reqnext;
223         char *b_data;
224 };
225
226 /*
227  *      Our view of a packet command.
228  */
229 typedef struct idetape_packet_command_s {
230         u8 c[12];                               /* Actual packet bytes */
231         int retries;                            /* On each retry, we increment retries */
232         int error;                              /* Error code */
233         int request_transfer;                   /* Bytes to transfer */
234         int actually_transferred;               /* Bytes actually transferred */
235         int buffer_size;                        /* Size of our data buffer */
236         struct idetape_bh *bh;
237         char *b_data;
238         int b_count;
239         u8 *buffer;                             /* Data buffer */
240         u8 *current_position;                   /* Pointer into the above buffer */
241         ide_startstop_t (*callback) (ide_drive_t *);    /* Called when this packet command is completed */
242         u8 pc_buffer[IDETAPE_PC_BUFFER_SIZE];   /* Temporary buffer */
243         unsigned long flags;                    /* Status/Action bit flags: long for set_bit */
244 } idetape_pc_t;
245
246 /*
247  *      Packet command flag bits.
248  */
249 /* Set when an error is considered normal - We won't retry */
250 #define PC_ABORT                        0
251 /* 1 When polling for DSC on a media access command */
252 #define PC_WAIT_FOR_DSC                 1
253 /* 1 when we prefer to use DMA if possible */
254 #define PC_DMA_RECOMMENDED              2
255 /* 1 while DMA in progress */
256 #define PC_DMA_IN_PROGRESS              3
257 /* 1 when encountered problem during DMA */
258 #define PC_DMA_ERROR                    4
259 /* Data direction */
260 #define PC_WRITING                      5
261
262 /*
263  *      Block Size Page
264  */
265 typedef struct {
266         unsigned        page_code       :6;     /* Page code - Should be 0x30 */
267         unsigned        reserved1_6     :1;
268         unsigned        ps              :1;
269         __u8            page_length;            /* Page Length - Should be 2 */
270         __u8            reserved2;
271         unsigned        play32          :1;
272         unsigned        play32_5        :1;
273         unsigned        reserved2_23    :2;
274         unsigned        record32        :1;
275         unsigned        record32_5      :1;
276         unsigned        reserved2_6     :1;
277         unsigned        one             :1;
278 } idetape_block_size_page_t;
279
280 /*
281  *      A pipeline stage.
282  */
283 typedef struct idetape_stage_s {
284         struct request rq;                      /* The corresponding request */
285         struct idetape_bh *bh;                  /* The data buffers */
286         struct idetape_stage_s *next;           /* Pointer to the next stage */
287 } idetape_stage_t;
288
289 /*
290  *      Most of our global data which we need to save even as we leave the
291  *      driver due to an interrupt or a timer event is stored in a variable
292  *      of type idetape_tape_t, defined below.
293  */
294 typedef struct ide_tape_obj {
295         ide_drive_t     *drive;
296         ide_driver_t    *driver;
297         struct gendisk  *disk;
298         struct kref     kref;
299
300         /*
301          *      Since a typical character device operation requires more
302          *      than one packet command, we provide here enough memory
303          *      for the maximum of interconnected packet commands.
304          *      The packet commands are stored in the circular array pc_stack.
305          *      pc_stack_index points to the last used entry, and warps around
306          *      to the start when we get to the last array entry.
307          *
308          *      pc points to the current processed packet command.
309          *
310          *      failed_pc points to the last failed packet command, or contains
311          *      NULL if we do not need to retry any packet command. This is
312          *      required since an additional packet command is needed before the
313          *      retry, to get detailed information on what went wrong.
314          */
315         /* Current packet command */
316         idetape_pc_t *pc;
317         /* Last failed packet command */
318         idetape_pc_t *failed_pc;
319         /* Packet command stack */
320         idetape_pc_t pc_stack[IDETAPE_PC_STACK];
321         /* Next free packet command storage space */
322         int pc_stack_index;
323         struct request rq_stack[IDETAPE_PC_STACK];
324         /* We implement a circular array */
325         int rq_stack_index;
326
327         /*
328          *      DSC polling variables.
329          *
330          *      While polling for DSC we use postponed_rq to postpone the
331          *      current request so that ide.c will be able to service
332          *      pending requests on the other device. Note that at most
333          *      we will have only one DSC (usually data transfer) request
334          *      in the device request queue. Additional requests can be
335          *      queued in our internal pipeline, but they will be visible
336          *      to ide.c only one at a time.
337          */
338         struct request *postponed_rq;
339         /* The time in which we started polling for DSC */
340         unsigned long dsc_polling_start;
341         /* Timer used to poll for dsc */
342         struct timer_list dsc_timer;
343         /* Read/Write dsc polling frequency */
344         unsigned long best_dsc_rw_frequency;
345         /* The current polling frequency */
346         unsigned long dsc_polling_frequency;
347         /* Maximum waiting time */
348         unsigned long dsc_timeout;
349
350         /*
351          *      Read position information
352          */
353         u8 partition;
354         /* Current block */
355         unsigned int first_frame_position;
356         unsigned int last_frame_position;
357         unsigned int blocks_in_buffer;
358
359         /*
360          *      Last error information
361          */
362         u8 sense_key, asc, ascq;
363
364         /*
365          *      Character device operation
366          */
367         unsigned int minor;
368         /* device name */
369         char name[4];
370         /* Current character device data transfer direction */
371         idetape_chrdev_direction_t chrdev_direction;
372
373         /*
374          *      Device information
375          */
376         /* Usually 512 or 1024 bytes */
377         unsigned short tape_block_size;
378         int user_bs_factor;
379
380         /* Copy of the tape's Capabilities and Mechanical Page */
381         u8 caps[20];
382
383         /*
384          *      Active data transfer request parameters.
385          *
386          *      At most, there is only one ide-tape originated data transfer
387          *      request in the device request queue. This allows ide.c to
388          *      easily service requests from the other device when we
389          *      postpone our active request. In the pipelined operation
390          *      mode, we use our internal pipeline structure to hold
391          *      more data requests.
392          *
393          *      The data buffer size is chosen based on the tape's
394          *      recommendation.
395          */
396         /* Pointer to the request which is waiting in the device request queue */
397         struct request *active_data_request;
398         /* Data buffer size (chosen based on the tape's recommendation */
399         int stage_size;
400         idetape_stage_t *merge_stage;
401         int merge_stage_size;
402         struct idetape_bh *bh;
403         char *b_data;
404         int b_count;
405         
406         /*
407          *      Pipeline parameters.
408          *
409          *      To accomplish non-pipelined mode, we simply set the following
410          *      variables to zero (or NULL, where appropriate).
411          */
412         /* Number of currently used stages */
413         int nr_stages;
414         /* Number of pending stages */
415         int nr_pending_stages;
416         /* We will not allocate more than this number of stages */
417         int max_stages, min_pipeline, max_pipeline;
418         /* The first stage which will be removed from the pipeline */
419         idetape_stage_t *first_stage;
420         /* The currently active stage */
421         idetape_stage_t *active_stage;
422         /* Will be serviced after the currently active request */
423         idetape_stage_t *next_stage;
424         /* New requests will be added to the pipeline here */
425         idetape_stage_t *last_stage;
426         /* Optional free stage which we can use */
427         idetape_stage_t *cache_stage;
428         int pages_per_stage;
429         /* Wasted space in each stage */
430         int excess_bh_size;
431
432         /* Status/Action flags: long for set_bit */
433         unsigned long flags;
434         /* protects the ide-tape queue */
435         spinlock_t spinlock;
436
437         /*
438          * Measures average tape speed
439          */
440         unsigned long avg_time;
441         int avg_size;
442         int avg_speed;
443
444         char vendor_id[10];
445         char product_id[18];
446         char firmware_revision[6];
447         int firmware_revision_num;
448
449         /* the door is currently locked */
450         int door_locked;
451         /* the tape hardware is write protected */
452         char drv_write_prot;
453         /* the tape is write protected (hardware or opened as read-only) */
454         char write_prot;
455
456         /*
457          * Limit the number of times a request can
458          * be postponed, to avoid an infinite postpone
459          * deadlock.
460          */
461         /* request postpone count limit */
462         int postpone_cnt;
463
464         /*
465          * Measures number of frames:
466          *
467          * 1. written/read to/from the driver pipeline (pipeline_head).
468          * 2. written/read to/from the tape buffers (idetape_bh).
469          * 3. written/read by the tape to/from the media (tape_head).
470          */
471         int pipeline_head;
472         int buffer_head;
473         int tape_head;
474         int last_tape_head;
475
476         /*
477          * Speed control at the tape buffers input/output
478          */
479         unsigned long insert_time;
480         int insert_size;
481         int insert_speed;
482         int max_insert_speed;
483         int measure_insert_time;
484
485         /*
486          * Measure tape still time, in milliseconds
487          */
488         unsigned long tape_still_time_begin;
489         int tape_still_time;
490
491         /*
492          * Speed regulation negative feedback loop
493          */
494         int speed_control;
495         int pipeline_head_speed;
496         int controlled_pipeline_head_speed;
497         int uncontrolled_pipeline_head_speed;
498         int controlled_last_pipeline_head;
499         int uncontrolled_last_pipeline_head;
500         unsigned long uncontrolled_pipeline_head_time;
501         unsigned long controlled_pipeline_head_time;
502         int controlled_previous_pipeline_head;
503         int uncontrolled_previous_pipeline_head;
504         unsigned long controlled_previous_head_time;
505         unsigned long uncontrolled_previous_head_time;
506         int restart_speed_control_req;
507
508         /*
509          * Debug_level determines amount of debugging output;
510          * can be changed using /proc/ide/hdx/settings
511          * 0 : almost no debugging output
512          * 1 : 0+output errors only
513          * 2 : 1+output all sensekey/asc
514          * 3 : 2+follow all chrdev related procedures
515          * 4 : 3+follow all procedures
516          * 5 : 4+include pc_stack rq_stack info
517          * 6 : 5+USE_COUNT updates
518          */
519          int debug_level; 
520 } idetape_tape_t;
521
522 static DEFINE_MUTEX(idetape_ref_mutex);
523
524 static struct class *idetape_sysfs_class;
525
526 #define to_ide_tape(obj) container_of(obj, struct ide_tape_obj, kref)
527
528 #define ide_tape_g(disk) \
529         container_of((disk)->private_data, struct ide_tape_obj, driver)
530
531 static struct ide_tape_obj *ide_tape_get(struct gendisk *disk)
532 {
533         struct ide_tape_obj *tape = NULL;
534
535         mutex_lock(&idetape_ref_mutex);
536         tape = ide_tape_g(disk);
537         if (tape)
538                 kref_get(&tape->kref);
539         mutex_unlock(&idetape_ref_mutex);
540         return tape;
541 }
542
543 static void ide_tape_release(struct kref *);
544
545 static void ide_tape_put(struct ide_tape_obj *tape)
546 {
547         mutex_lock(&idetape_ref_mutex);
548         kref_put(&tape->kref, ide_tape_release);
549         mutex_unlock(&idetape_ref_mutex);
550 }
551
552 /*
553  *      Tape door status
554  */
555 #define DOOR_UNLOCKED                   0
556 #define DOOR_LOCKED                     1
557 #define DOOR_EXPLICITLY_LOCKED          2
558
559 /*
560  *      Tape flag bits values.
561  */
562 #define IDETAPE_IGNORE_DSC              0
563 #define IDETAPE_ADDRESS_VALID           1       /* 0 When the tape position is unknown */
564 #define IDETAPE_BUSY                    2       /* Device already opened */
565 #define IDETAPE_PIPELINE_ERROR          3       /* Error detected in a pipeline stage */
566 #define IDETAPE_DETECT_BS               4       /* Attempt to auto-detect the current user block size */
567 #define IDETAPE_FILEMARK                5       /* Currently on a filemark */
568 #define IDETAPE_DRQ_INTERRUPT           6       /* DRQ interrupt device */
569 #define IDETAPE_READ_ERROR              7
570 #define IDETAPE_PIPELINE_ACTIVE         8       /* pipeline active */
571 /* 0 = no tape is loaded, so we don't rewind after ejecting */
572 #define IDETAPE_MEDIUM_PRESENT          9
573
574 /*
575  *      Supported ATAPI tape drives packet commands
576  */
577 #define IDETAPE_TEST_UNIT_READY_CMD     0x00
578 #define IDETAPE_REWIND_CMD              0x01
579 #define IDETAPE_REQUEST_SENSE_CMD       0x03
580 #define IDETAPE_READ_CMD                0x08
581 #define IDETAPE_WRITE_CMD               0x0a
582 #define IDETAPE_WRITE_FILEMARK_CMD      0x10
583 #define IDETAPE_SPACE_CMD               0x11
584 #define IDETAPE_INQUIRY_CMD             0x12
585 #define IDETAPE_ERASE_CMD               0x19
586 #define IDETAPE_MODE_SENSE_CMD          0x1a
587 #define IDETAPE_MODE_SELECT_CMD         0x15
588 #define IDETAPE_LOAD_UNLOAD_CMD         0x1b
589 #define IDETAPE_PREVENT_CMD             0x1e
590 #define IDETAPE_LOCATE_CMD              0x2b
591 #define IDETAPE_READ_POSITION_CMD       0x34
592 #define IDETAPE_READ_BUFFER_CMD         0x3c
593 #define IDETAPE_SET_SPEED_CMD           0xbb
594
595 /*
596  *      Some defines for the READ BUFFER command
597  */
598 #define IDETAPE_RETRIEVE_FAULTY_BLOCK   6
599
600 /*
601  *      Some defines for the SPACE command
602  */
603 #define IDETAPE_SPACE_OVER_FILEMARK     1
604 #define IDETAPE_SPACE_TO_EOD            3
605
606 /*
607  *      Some defines for the LOAD UNLOAD command
608  */
609 #define IDETAPE_LU_LOAD_MASK            1
610 #define IDETAPE_LU_RETENSION_MASK       2
611 #define IDETAPE_LU_EOT_MASK             4
612
613 /*
614  *      Special requests for our block device strategy routine.
615  *
616  *      In order to service a character device command, we add special
617  *      requests to the tail of our block device request queue and wait
618  *      for their completion.
619  */
620
621 enum {
622         REQ_IDETAPE_PC1         = (1 << 0), /* packet command (first stage) */
623         REQ_IDETAPE_PC2         = (1 << 1), /* packet command (second stage) */
624         REQ_IDETAPE_READ        = (1 << 2),
625         REQ_IDETAPE_WRITE       = (1 << 3),
626         REQ_IDETAPE_READ_BUFFER = (1 << 4),
627 };
628
629 /*
630  *      Error codes which are returned in rq->errors to the higher part
631  *      of the driver.
632  */
633 #define IDETAPE_ERROR_GENERAL           101
634 #define IDETAPE_ERROR_FILEMARK          102
635 #define IDETAPE_ERROR_EOD               103
636
637 /*
638  *      The following is used to format the general configuration word of
639  *      the ATAPI IDENTIFY DEVICE command.
640  */
641 struct idetape_id_gcw { 
642         unsigned packet_size            :2;     /* Packet Size */
643         unsigned reserved234            :3;     /* Reserved */
644         unsigned drq_type               :2;     /* Command packet DRQ type */
645         unsigned removable              :1;     /* Removable media */
646         unsigned device_type            :5;     /* Device type */
647         unsigned reserved13             :1;     /* Reserved */
648         unsigned protocol               :2;     /* Protocol type */
649 };
650
651 /*
652  *      READ POSITION packet command - Data Format (From Table 6-57)
653  */
654 typedef struct {
655         unsigned        reserved0_10    :2;     /* Reserved */
656         unsigned        bpu             :1;     /* Block Position Unknown */    
657         unsigned        reserved0_543   :3;     /* Reserved */
658         unsigned        eop             :1;     /* End Of Partition */
659         unsigned        bop             :1;     /* Beginning Of Partition */
660         u8              partition;              /* Partition Number */
661         u8              reserved2, reserved3;   /* Reserved */
662         u32             first_block;            /* First Block Location */
663         u32             last_block;             /* Last Block Location (Optional) */
664         u8              reserved12;             /* Reserved */
665         u8              blocks_in_buffer[3];    /* Blocks In Buffer - (Optional) */
666         u32             bytes_in_buffer;        /* Bytes In Buffer (Optional) */
667 } idetape_read_position_result_t;
668
669 /*
670  *      Follows structures which are related to the SELECT SENSE / MODE SENSE
671  *      packet commands. Those packet commands are still not supported
672  *      by ide-tape.
673  */
674 #define IDETAPE_BLOCK_DESCRIPTOR        0
675 #define IDETAPE_CAPABILITIES_PAGE       0x2a
676 #define IDETAPE_PARAMTR_PAGE            0x2b   /* Onstream DI-x0 only */
677 #define IDETAPE_BLOCK_SIZE_PAGE         0x30
678 #define IDETAPE_BUFFER_FILLING_PAGE     0x33
679
680 /*
681  *      Mode Parameter Block Descriptor the MODE SENSE packet command
682  *
683  *      Support for block descriptors is optional.
684  */
685 typedef struct {
686         __u8            density_code;           /* Medium density code */
687         __u8            blocks[3];              /* Number of blocks */
688         __u8            reserved4;              /* Reserved */
689         __u8            length[3];              /* Block Length */
690 } idetape_parameter_block_descriptor_t;
691
692 /*
693  *      The Medium Partition Page, as returned by the MODE SENSE packet command.
694  */
695 typedef struct {
696         unsigned        page_code       :6;     /* Page Code - Should be 0x11 */
697         unsigned        reserved1_6     :1;     /* Reserved */
698         unsigned        ps              :1;
699         __u8            page_length;            /* Page Length - Should be 6 */
700         __u8            map;                    /* Maximum Additional Partitions - Should be 0 */
701         __u8            apd;                    /* Additional Partitions Defined - Should be 0 */
702         unsigned        reserved4_012   :3;     /* Reserved */
703         unsigned        psum            :2;     /* Should be 0 */
704         unsigned        idp             :1;     /* Should be 0 */
705         unsigned        sdp             :1;     /* Should be 0 */
706         unsigned        fdp             :1;     /* Fixed Data Partitions */
707         __u8            mfr;                    /* Medium Format Recognition */
708         __u8            reserved[2];            /* Reserved */
709 } idetape_medium_partition_page_t;
710
711 /*
712  *      Run time configurable parameters.
713  */
714 typedef struct {
715         int     dsc_rw_frequency;
716         int     dsc_media_access_frequency;
717         int     nr_stages;
718 } idetape_config_t;
719
720 /*
721  *      The variables below are used for the character device interface.
722  *      Additional state variables are defined in our ide_drive_t structure.
723  */
724 static struct ide_tape_obj * idetape_devs[MAX_HWIFS * MAX_DRIVES];
725
726 #define ide_tape_f(file) ((file)->private_data)
727
728 static struct ide_tape_obj *ide_tape_chrdev_get(unsigned int i)
729 {
730         struct ide_tape_obj *tape = NULL;
731
732         mutex_lock(&idetape_ref_mutex);
733         tape = idetape_devs[i];
734         if (tape)
735                 kref_get(&tape->kref);
736         mutex_unlock(&idetape_ref_mutex);
737         return tape;
738 }
739
740 /*
741  *      Function declarations
742  *
743  */
744 static int idetape_chrdev_release (struct inode *inode, struct file *filp);
745 static void idetape_write_release (ide_drive_t *drive, unsigned int minor);
746
747 /*
748  * Too bad. The drive wants to send us data which we are not ready to accept.
749  * Just throw it away.
750  */
751 static void idetape_discard_data (ide_drive_t *drive, unsigned int bcount)
752 {
753         while (bcount--)
754                 (void) HWIF(drive)->INB(IDE_DATA_REG);
755 }
756
757 static void idetape_input_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
758 {
759         struct idetape_bh *bh = pc->bh;
760         int count;
761
762         while (bcount) {
763                 if (bh == NULL) {
764                         printk(KERN_ERR "ide-tape: bh == NULL in "
765                                 "idetape_input_buffers\n");
766                         idetape_discard_data(drive, bcount);
767                         return;
768                 }
769                 count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), bcount);
770                 HWIF(drive)->atapi_input_bytes(drive, bh->b_data + atomic_read(&bh->b_count), count);
771                 bcount -= count;
772                 atomic_add(count, &bh->b_count);
773                 if (atomic_read(&bh->b_count) == bh->b_size) {
774                         bh = bh->b_reqnext;
775                         if (bh)
776                                 atomic_set(&bh->b_count, 0);
777                 }
778         }
779         pc->bh = bh;
780 }
781
782 static void idetape_output_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
783 {
784         struct idetape_bh *bh = pc->bh;
785         int count;
786
787         while (bcount) {
788                 if (bh == NULL) {
789                         printk(KERN_ERR "ide-tape: bh == NULL in "
790                                 "idetape_output_buffers\n");
791                         return;
792                 }
793                 count = min((unsigned int)pc->b_count, (unsigned int)bcount);
794                 HWIF(drive)->atapi_output_bytes(drive, pc->b_data, count);
795                 bcount -= count;
796                 pc->b_data += count;
797                 pc->b_count -= count;
798                 if (!pc->b_count) {
799                         pc->bh = bh = bh->b_reqnext;
800                         if (bh) {
801                                 pc->b_data = bh->b_data;
802                                 pc->b_count = atomic_read(&bh->b_count);
803                         }
804                 }
805         }
806 }
807
808 static void idetape_update_buffers (idetape_pc_t *pc)
809 {
810         struct idetape_bh *bh = pc->bh;
811         int count;
812         unsigned int bcount = pc->actually_transferred;
813
814         if (test_bit(PC_WRITING, &pc->flags))
815                 return;
816         while (bcount) {
817                 if (bh == NULL) {
818                         printk(KERN_ERR "ide-tape: bh == NULL in "
819                                 "idetape_update_buffers\n");
820                         return;
821                 }
822                 count = min((unsigned int)bh->b_size, (unsigned int)bcount);
823                 atomic_set(&bh->b_count, count);
824                 if (atomic_read(&bh->b_count) == bh->b_size)
825                         bh = bh->b_reqnext;
826                 bcount -= count;
827         }
828         pc->bh = bh;
829 }
830
831 /*
832  *      idetape_next_pc_storage returns a pointer to a place in which we can
833  *      safely store a packet command, even though we intend to leave the
834  *      driver. A storage space for a maximum of IDETAPE_PC_STACK packet
835  *      commands is allocated at initialization time.
836  */
837 static idetape_pc_t *idetape_next_pc_storage (ide_drive_t *drive)
838 {
839         idetape_tape_t *tape = drive->driver_data;
840
841 #if IDETAPE_DEBUG_LOG
842         if (tape->debug_level >= 5)
843                 printk(KERN_INFO "ide-tape: pc_stack_index=%d\n",
844                         tape->pc_stack_index);
845 #endif /* IDETAPE_DEBUG_LOG */
846         if (tape->pc_stack_index == IDETAPE_PC_STACK)
847                 tape->pc_stack_index=0;
848         return (&tape->pc_stack[tape->pc_stack_index++]);
849 }
850
851 /*
852  *      idetape_next_rq_storage is used along with idetape_next_pc_storage.
853  *      Since we queue packet commands in the request queue, we need to
854  *      allocate a request, along with the allocation of a packet command.
855  */
856  
857 /**************************************************************
858  *                                                            *
859  *  This should get fixed to use kmalloc(.., GFP_ATOMIC)      *
860  *  followed later on by kfree().   -ml                       *
861  *                                                            *
862  **************************************************************/
863  
864 static struct request *idetape_next_rq_storage (ide_drive_t *drive)
865 {
866         idetape_tape_t *tape = drive->driver_data;
867
868 #if IDETAPE_DEBUG_LOG
869         if (tape->debug_level >= 5)
870                 printk(KERN_INFO "ide-tape: rq_stack_index=%d\n",
871                         tape->rq_stack_index);
872 #endif /* IDETAPE_DEBUG_LOG */
873         if (tape->rq_stack_index == IDETAPE_PC_STACK)
874                 tape->rq_stack_index=0;
875         return (&tape->rq_stack[tape->rq_stack_index++]);
876 }
877
878 /*
879  *      idetape_init_pc initializes a packet command.
880  */
881 static void idetape_init_pc (idetape_pc_t *pc)
882 {
883         memset(pc->c, 0, 12);
884         pc->retries = 0;
885         pc->flags = 0;
886         pc->request_transfer = 0;
887         pc->buffer = pc->pc_buffer;
888         pc->buffer_size = IDETAPE_PC_BUFFER_SIZE;
889         pc->bh = NULL;
890         pc->b_data = NULL;
891 }
892
893 /*
894  * called on each failed packet command retry to analyze the request sense. We
895  * currently do not utilize this information.
896  */
897 static void idetape_analyze_error(ide_drive_t *drive, u8 *sense)
898 {
899         idetape_tape_t *tape = drive->driver_data;
900         idetape_pc_t *pc = tape->failed_pc;
901
902         tape->sense_key = sense[2] & 0xF;
903         tape->asc       = sense[12];
904         tape->ascq      = sense[13];
905 #if IDETAPE_DEBUG_LOG
906         /*
907          * Without debugging, we only log an error if we decided to give up
908          * retrying.
909          */
910         if (tape->debug_level >= 1)
911                 printk(KERN_INFO "ide-tape: pc = %x, sense key = %x, "
912                         "asc = %x, ascq = %x\n",
913                         pc->c[0], tape->sense_key,
914                         tape->asc, tape->ascq);
915 #endif /* IDETAPE_DEBUG_LOG */
916
917         /* Correct pc->actually_transferred by asking the tape.  */
918         if (test_bit(PC_DMA_ERROR, &pc->flags)) {
919                 pc->actually_transferred = pc->request_transfer -
920                         tape->tape_block_size *
921                         ntohl(get_unaligned((u32 *)&sense[3]));
922                 idetape_update_buffers(pc);
923         }
924
925         /*
926          * If error was the result of a zero-length read or write command,
927          * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
928          * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
929          */
930         if ((pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD)
931             /* length == 0 */
932             && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
933                 if (tape->sense_key == 5) {
934                         /* don't report an error, everything's ok */
935                         pc->error = 0;
936                         /* don't retry read/write */
937                         set_bit(PC_ABORT, &pc->flags);
938                 }
939         }
940         if (pc->c[0] == IDETAPE_READ_CMD && (sense[2] & 0x80)) {
941                 pc->error = IDETAPE_ERROR_FILEMARK;
942                 set_bit(PC_ABORT, &pc->flags);
943         }
944         if (pc->c[0] == IDETAPE_WRITE_CMD) {
945                 if ((sense[2] & 0x40) || (tape->sense_key == 0xd
946                      && tape->asc == 0x0 && tape->ascq == 0x2)) {
947                         pc->error = IDETAPE_ERROR_EOD;
948                         set_bit(PC_ABORT, &pc->flags);
949                 }
950         }
951         if (pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD) {
952                 if (tape->sense_key == 8) {
953                         pc->error = IDETAPE_ERROR_EOD;
954                         set_bit(PC_ABORT, &pc->flags);
955                 }
956                 if (!test_bit(PC_ABORT, &pc->flags) &&
957                     pc->actually_transferred)
958                         pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
959         }
960 }
961
962 /*
963  * idetape_active_next_stage will declare the next stage as "active".
964  */
965 static void idetape_active_next_stage (ide_drive_t *drive)
966 {
967         idetape_tape_t *tape = drive->driver_data;
968         idetape_stage_t *stage = tape->next_stage;
969         struct request *rq = &stage->rq;
970
971 #if IDETAPE_DEBUG_LOG
972         if (tape->debug_level >= 4)
973                 printk(KERN_INFO "ide-tape: Reached idetape_active_next_stage\n");
974 #endif /* IDETAPE_DEBUG_LOG */
975         if (stage == NULL) {
976                 printk(KERN_ERR "ide-tape: bug: Trying to activate a non existing stage\n");
977                 return;
978         }
979
980         rq->rq_disk = tape->disk;
981         rq->buffer = NULL;
982         rq->special = (void *)stage->bh;
983         tape->active_data_request = rq;
984         tape->active_stage = stage;
985         tape->next_stage = stage->next;
986 }
987
988 /*
989  *      idetape_increase_max_pipeline_stages is a part of the feedback
990  *      loop which tries to find the optimum number of stages. In the
991  *      feedback loop, we are starting from a minimum maximum number of
992  *      stages, and if we sense that the pipeline is empty, we try to
993  *      increase it, until we reach the user compile time memory limit.
994  */
995 static void idetape_increase_max_pipeline_stages (ide_drive_t *drive)
996 {
997         idetape_tape_t *tape = drive->driver_data;
998         int increase = (tape->max_pipeline - tape->min_pipeline) / 10;
999         
1000 #if IDETAPE_DEBUG_LOG
1001         if (tape->debug_level >= 4)
1002                 printk (KERN_INFO "ide-tape: Reached idetape_increase_max_pipeline_stages\n");
1003 #endif /* IDETAPE_DEBUG_LOG */
1004
1005         tape->max_stages += max(increase, 1);
1006         tape->max_stages = max(tape->max_stages, tape->min_pipeline);
1007         tape->max_stages = min(tape->max_stages, tape->max_pipeline);
1008 }
1009
1010 /*
1011  *      idetape_kfree_stage calls kfree to completely free a stage, along with
1012  *      its related buffers.
1013  */
1014 static void __idetape_kfree_stage (idetape_stage_t *stage)
1015 {
1016         struct idetape_bh *prev_bh, *bh = stage->bh;
1017         int size;
1018
1019         while (bh != NULL) {
1020                 if (bh->b_data != NULL) {
1021                         size = (int) bh->b_size;
1022                         while (size > 0) {
1023                                 free_page((unsigned long) bh->b_data);
1024                                 size -= PAGE_SIZE;
1025                                 bh->b_data += PAGE_SIZE;
1026                         }
1027                 }
1028                 prev_bh = bh;
1029                 bh = bh->b_reqnext;
1030                 kfree(prev_bh);
1031         }
1032         kfree(stage);
1033 }
1034
1035 static void idetape_kfree_stage (idetape_tape_t *tape, idetape_stage_t *stage)
1036 {
1037         __idetape_kfree_stage(stage);
1038 }
1039
1040 /*
1041  *      idetape_remove_stage_head removes tape->first_stage from the pipeline.
1042  *      The caller should avoid race conditions.
1043  */
1044 static void idetape_remove_stage_head (ide_drive_t *drive)
1045 {
1046         idetape_tape_t *tape = drive->driver_data;
1047         idetape_stage_t *stage;
1048         
1049 #if IDETAPE_DEBUG_LOG
1050         if (tape->debug_level >= 4)
1051                 printk(KERN_INFO "ide-tape: Reached idetape_remove_stage_head\n");
1052 #endif /* IDETAPE_DEBUG_LOG */
1053         if (tape->first_stage == NULL) {
1054                 printk(KERN_ERR "ide-tape: bug: tape->first_stage is NULL\n");
1055                 return;
1056         }
1057         if (tape->active_stage == tape->first_stage) {
1058                 printk(KERN_ERR "ide-tape: bug: Trying to free our active pipeline stage\n");
1059                 return;
1060         }
1061         stage = tape->first_stage;
1062         tape->first_stage = stage->next;
1063         idetape_kfree_stage(tape, stage);
1064         tape->nr_stages--;
1065         if (tape->first_stage == NULL) {
1066                 tape->last_stage = NULL;
1067                 if (tape->next_stage != NULL)
1068                         printk(KERN_ERR "ide-tape: bug: tape->next_stage != NULL\n");
1069                 if (tape->nr_stages)
1070                         printk(KERN_ERR "ide-tape: bug: nr_stages should be 0 now\n");
1071         }
1072 }
1073
1074 /*
1075  * This will free all the pipeline stages starting from new_last_stage->next
1076  * to the end of the list, and point tape->last_stage to new_last_stage.
1077  */
1078 static void idetape_abort_pipeline(ide_drive_t *drive,
1079                                    idetape_stage_t *new_last_stage)
1080 {
1081         idetape_tape_t *tape = drive->driver_data;
1082         idetape_stage_t *stage = new_last_stage->next;
1083         idetape_stage_t *nstage;
1084
1085 #if IDETAPE_DEBUG_LOG
1086         if (tape->debug_level >= 4)
1087                 printk(KERN_INFO "ide-tape: %s: idetape_abort_pipeline called\n", tape->name);
1088 #endif
1089         while (stage) {
1090                 nstage = stage->next;
1091                 idetape_kfree_stage(tape, stage);
1092                 --tape->nr_stages;
1093                 --tape->nr_pending_stages;
1094                 stage = nstage;
1095         }
1096         if (new_last_stage)
1097                 new_last_stage->next = NULL;
1098         tape->last_stage = new_last_stage;
1099         tape->next_stage = NULL;
1100 }
1101
1102 /*
1103  *      idetape_end_request is used to finish servicing a request, and to
1104  *      insert a pending pipeline request into the main device queue.
1105  */
1106 static int idetape_end_request(ide_drive_t *drive, int uptodate, int nr_sects)
1107 {
1108         struct request *rq = HWGROUP(drive)->rq;
1109         idetape_tape_t *tape = drive->driver_data;
1110         unsigned long flags;
1111         int error;
1112         int remove_stage = 0;
1113         idetape_stage_t *active_stage;
1114
1115 #if IDETAPE_DEBUG_LOG
1116         if (tape->debug_level >= 4)
1117         printk(KERN_INFO "ide-tape: Reached idetape_end_request\n");
1118 #endif /* IDETAPE_DEBUG_LOG */
1119
1120         switch (uptodate) {
1121                 case 0: error = IDETAPE_ERROR_GENERAL; break;
1122                 case 1: error = 0; break;
1123                 default: error = uptodate;
1124         }
1125         rq->errors = error;
1126         if (error)
1127                 tape->failed_pc = NULL;
1128
1129         if (!blk_special_request(rq)) {
1130                 ide_end_request(drive, uptodate, nr_sects);
1131                 return 0;
1132         }
1133
1134         spin_lock_irqsave(&tape->spinlock, flags);
1135
1136         /* The request was a pipelined data transfer request */
1137         if (tape->active_data_request == rq) {
1138                 active_stage = tape->active_stage;
1139                 tape->active_stage = NULL;
1140                 tape->active_data_request = NULL;
1141                 tape->nr_pending_stages--;
1142                 if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
1143                         remove_stage = 1;
1144                         if (error) {
1145                                 set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1146                                 if (error == IDETAPE_ERROR_EOD)
1147                                         idetape_abort_pipeline(drive, active_stage);
1148                         }
1149                 } else if (rq->cmd[0] & REQ_IDETAPE_READ) {
1150                         if (error == IDETAPE_ERROR_EOD) {
1151                                 set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1152                                 idetape_abort_pipeline(drive, active_stage);
1153                         }
1154                 }
1155                 if (tape->next_stage != NULL) {
1156                         idetape_active_next_stage(drive);
1157
1158                         /*
1159                          * Insert the next request into the request queue.
1160                          */
1161                         (void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
1162                 } else if (!error) {
1163                                 idetape_increase_max_pipeline_stages(drive);
1164                 }
1165         }
1166         ide_end_drive_cmd(drive, 0, 0);
1167 //      blkdev_dequeue_request(rq);
1168 //      drive->rq = NULL;
1169 //      end_that_request_last(rq);
1170
1171         if (remove_stage)
1172                 idetape_remove_stage_head(drive);
1173         if (tape->active_data_request == NULL)
1174                 clear_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
1175         spin_unlock_irqrestore(&tape->spinlock, flags);
1176         return 0;
1177 }
1178
1179 static ide_startstop_t idetape_request_sense_callback (ide_drive_t *drive)
1180 {
1181         idetape_tape_t *tape = drive->driver_data;
1182
1183 #if IDETAPE_DEBUG_LOG
1184         if (tape->debug_level >= 4)
1185                 printk(KERN_INFO "ide-tape: Reached idetape_request_sense_callback\n");
1186 #endif /* IDETAPE_DEBUG_LOG */
1187         if (!tape->pc->error) {
1188                 idetape_analyze_error(drive, tape->pc->buffer);
1189                 idetape_end_request(drive, 1, 0);
1190         } else {
1191                 printk(KERN_ERR "ide-tape: Error in REQUEST SENSE itself - Aborting request!\n");
1192                 idetape_end_request(drive, 0, 0);
1193         }
1194         return ide_stopped;
1195 }
1196
1197 static void idetape_create_request_sense_cmd (idetape_pc_t *pc)
1198 {
1199         idetape_init_pc(pc);    
1200         pc->c[0] = IDETAPE_REQUEST_SENSE_CMD;
1201         pc->c[4] = 20;
1202         pc->request_transfer = 20;
1203         pc->callback = &idetape_request_sense_callback;
1204 }
1205
1206 static void idetape_init_rq(struct request *rq, u8 cmd)
1207 {
1208         memset(rq, 0, sizeof(*rq));
1209         rq->cmd_type = REQ_TYPE_SPECIAL;
1210         rq->cmd[0] = cmd;
1211 }
1212
1213 /*
1214  *      idetape_queue_pc_head generates a new packet command request in front
1215  *      of the request queue, before the current request, so that it will be
1216  *      processed immediately, on the next pass through the driver.
1217  *
1218  *      idetape_queue_pc_head is called from the request handling part of
1219  *      the driver (the "bottom" part). Safe storage for the request should
1220  *      be allocated with idetape_next_pc_storage and idetape_next_rq_storage
1221  *      before calling idetape_queue_pc_head.
1222  *
1223  *      Memory for those requests is pre-allocated at initialization time, and
1224  *      is limited to IDETAPE_PC_STACK requests. We assume that we have enough
1225  *      space for the maximum possible number of inter-dependent packet commands.
1226  *
1227  *      The higher level of the driver - The ioctl handler and the character
1228  *      device handling functions should queue request to the lower level part
1229  *      and wait for their completion using idetape_queue_pc_tail or
1230  *      idetape_queue_rw_tail.
1231  */
1232 static void idetape_queue_pc_head (ide_drive_t *drive, idetape_pc_t *pc,struct request *rq)
1233 {
1234         struct ide_tape_obj *tape = drive->driver_data;
1235
1236         idetape_init_rq(rq, REQ_IDETAPE_PC1);
1237         rq->buffer = (char *) pc;
1238         rq->rq_disk = tape->disk;
1239         (void) ide_do_drive_cmd(drive, rq, ide_preempt);
1240 }
1241
1242 /*
1243  *      idetape_retry_pc is called when an error was detected during the
1244  *      last packet command. We queue a request sense packet command in
1245  *      the head of the request list.
1246  */
1247 static ide_startstop_t idetape_retry_pc (ide_drive_t *drive)
1248 {
1249         idetape_tape_t *tape = drive->driver_data;
1250         idetape_pc_t *pc;
1251         struct request *rq;
1252
1253         (void)drive->hwif->INB(IDE_ERROR_REG);
1254         pc = idetape_next_pc_storage(drive);
1255         rq = idetape_next_rq_storage(drive);
1256         idetape_create_request_sense_cmd(pc);
1257         set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
1258         idetape_queue_pc_head(drive, pc, rq);
1259         return ide_stopped;
1260 }
1261
1262 /*
1263  *      idetape_postpone_request postpones the current request so that
1264  *      ide.c will be able to service requests from another device on
1265  *      the same hwgroup while we are polling for DSC.
1266  */
1267 static void idetape_postpone_request (ide_drive_t *drive)
1268 {
1269         idetape_tape_t *tape = drive->driver_data;
1270
1271 #if IDETAPE_DEBUG_LOG
1272         if (tape->debug_level >= 4)
1273                 printk(KERN_INFO "ide-tape: idetape_postpone_request\n");
1274 #endif
1275         tape->postponed_rq = HWGROUP(drive)->rq;
1276         ide_stall_queue(drive, tape->dsc_polling_frequency);
1277 }
1278
1279 /*
1280  *      idetape_pc_intr is the usual interrupt handler which will be called
1281  *      during a packet command. We will transfer some of the data (as
1282  *      requested by the drive) and will re-point interrupt handler to us.
1283  *      When data transfer is finished, we will act according to the
1284  *      algorithm described before idetape_issue_packet_command.
1285  *
1286  */
1287 static ide_startstop_t idetape_pc_intr (ide_drive_t *drive)
1288 {
1289         ide_hwif_t *hwif = drive->hwif;
1290         idetape_tape_t *tape = drive->driver_data;
1291         idetape_pc_t *pc = tape->pc;
1292         unsigned int temp;
1293 #if SIMULATE_ERRORS
1294         static int error_sim_count = 0;
1295 #endif
1296         u16 bcount;
1297         u8 stat, ireason;
1298
1299 #if IDETAPE_DEBUG_LOG
1300         if (tape->debug_level >= 4)
1301                 printk(KERN_INFO "ide-tape: Reached idetape_pc_intr "
1302                                 "interrupt handler\n");
1303 #endif /* IDETAPE_DEBUG_LOG */  
1304
1305         /* Clear the interrupt */
1306         stat = hwif->INB(IDE_STATUS_REG);
1307
1308         if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
1309                 if (hwif->ide_dma_end(drive) || (stat & ERR_STAT)) {
1310                         /*
1311                          * A DMA error is sometimes expected. For example,
1312                          * if the tape is crossing a filemark during a
1313                          * READ command, it will issue an irq and position
1314                          * itself before the filemark, so that only a partial
1315                          * data transfer will occur (which causes the DMA
1316                          * error). In that case, we will later ask the tape
1317                          * how much bytes of the original request were
1318                          * actually transferred (we can't receive that
1319                          * information from the DMA engine on most chipsets).
1320                          */
1321
1322                         /*
1323                          * On the contrary, a DMA error is never expected;
1324                          * it usually indicates a hardware error or abort.
1325                          * If the tape crosses a filemark during a READ
1326                          * command, it will issue an irq and position itself
1327                          * after the filemark (not before). Only a partial
1328                          * data transfer will occur, but no DMA error.
1329                          * (AS, 19 Apr 2001)
1330                          */
1331                         set_bit(PC_DMA_ERROR, &pc->flags);
1332                 } else {
1333                         pc->actually_transferred = pc->request_transfer;
1334                         idetape_update_buffers(pc);
1335                 }
1336 #if IDETAPE_DEBUG_LOG
1337                 if (tape->debug_level >= 4)
1338                         printk(KERN_INFO "ide-tape: DMA finished\n");
1339 #endif /* IDETAPE_DEBUG_LOG */
1340         }
1341
1342         /* No more interrupts */
1343         if ((stat & DRQ_STAT) == 0) {
1344 #if IDETAPE_DEBUG_LOG
1345                 if (tape->debug_level >= 2)
1346                         printk(KERN_INFO "ide-tape: Packet command completed, %d bytes transferred\n", pc->actually_transferred);
1347 #endif /* IDETAPE_DEBUG_LOG */
1348                 clear_bit(PC_DMA_IN_PROGRESS, &pc->flags);
1349
1350                 local_irq_enable();
1351
1352 #if SIMULATE_ERRORS
1353                 if ((pc->c[0] == IDETAPE_WRITE_CMD ||
1354                      pc->c[0] == IDETAPE_READ_CMD) &&
1355                     (++error_sim_count % 100) == 0) {
1356                         printk(KERN_INFO "ide-tape: %s: simulating error\n",
1357                                 tape->name);
1358                         stat |= ERR_STAT;
1359                 }
1360 #endif
1361                 if ((stat & ERR_STAT) && pc->c[0] == IDETAPE_REQUEST_SENSE_CMD)
1362                         stat &= ~ERR_STAT;
1363                 if ((stat & ERR_STAT) || test_bit(PC_DMA_ERROR, &pc->flags)) {
1364                         /* Error detected */
1365 #if IDETAPE_DEBUG_LOG
1366                         if (tape->debug_level >= 1)
1367                                 printk(KERN_INFO "ide-tape: %s: I/O error\n",
1368                                         tape->name);
1369 #endif /* IDETAPE_DEBUG_LOG */
1370                         if (pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1371                                 printk(KERN_ERR "ide-tape: I/O error in request sense command\n");
1372                                 return ide_do_reset(drive);
1373                         }
1374 #if IDETAPE_DEBUG_LOG
1375                         if (tape->debug_level >= 1)
1376                                 printk(KERN_INFO "ide-tape: [cmd %x]: check condition\n", pc->c[0]);
1377 #endif
1378                         /* Retry operation */
1379                         return idetape_retry_pc(drive);
1380                 }
1381                 pc->error = 0;
1382                 if (test_bit(PC_WAIT_FOR_DSC, &pc->flags) &&
1383                     (stat & SEEK_STAT) == 0) {
1384                         /* Media access command */
1385                         tape->dsc_polling_start = jiffies;
1386                         tape->dsc_polling_frequency = IDETAPE_DSC_MA_FAST;
1387                         tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
1388                         /* Allow ide.c to handle other requests */
1389                         idetape_postpone_request(drive);
1390                         return ide_stopped;
1391                 }
1392                 if (tape->failed_pc == pc)
1393                         tape->failed_pc = NULL;
1394                 /* Command finished - Call the callback function */
1395                 return pc->callback(drive);
1396         }
1397         if (test_and_clear_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
1398                 printk(KERN_ERR "ide-tape: The tape wants to issue more "
1399                                 "interrupts in DMA mode\n");
1400                 printk(KERN_ERR "ide-tape: DMA disabled, reverting to PIO\n");
1401                 ide_dma_off(drive);
1402                 return ide_do_reset(drive);
1403         }
1404         /* Get the number of bytes to transfer on this interrupt. */
1405         bcount = (hwif->INB(IDE_BCOUNTH_REG) << 8) |
1406                   hwif->INB(IDE_BCOUNTL_REG);
1407
1408         ireason = hwif->INB(IDE_IREASON_REG);
1409
1410         if (ireason & CD) {
1411                 printk(KERN_ERR "ide-tape: CoD != 0 in idetape_pc_intr\n");
1412                 return ide_do_reset(drive);
1413         }
1414         if (((ireason & IO) == IO) == test_bit(PC_WRITING, &pc->flags)) {
1415                 /* Hopefully, we will never get here */
1416                 printk(KERN_ERR "ide-tape: We wanted to %s, ",
1417                                 (ireason & IO) ? "Write" : "Read");
1418                 printk(KERN_ERR "ide-tape: but the tape wants us to %s !\n",
1419                                 (ireason & IO) ? "Read" : "Write");
1420                 return ide_do_reset(drive);
1421         }
1422         if (!test_bit(PC_WRITING, &pc->flags)) {
1423                 /* Reading - Check that we have enough space */
1424                 temp = pc->actually_transferred + bcount;
1425                 if (temp > pc->request_transfer) {
1426                         if (temp > pc->buffer_size) {
1427                                 printk(KERN_ERR "ide-tape: The tape wants to send us more data than expected - discarding data\n");
1428                                 idetape_discard_data(drive, bcount);
1429                                 ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1430                                 return ide_started;
1431                         }
1432 #if IDETAPE_DEBUG_LOG
1433                         if (tape->debug_level >= 2)
1434                                 printk(KERN_NOTICE "ide-tape: The tape wants to send us more data than expected - allowing transfer\n");
1435 #endif /* IDETAPE_DEBUG_LOG */
1436                 }
1437         }
1438         if (test_bit(PC_WRITING, &pc->flags)) {
1439                 if (pc->bh != NULL)
1440                         idetape_output_buffers(drive, pc, bcount);
1441                 else
1442                         /* Write the current buffer */
1443                         hwif->atapi_output_bytes(drive, pc->current_position,
1444                                                  bcount);
1445         } else {
1446                 if (pc->bh != NULL)
1447                         idetape_input_buffers(drive, pc, bcount);
1448                 else
1449                         /* Read the current buffer */
1450                         hwif->atapi_input_bytes(drive, pc->current_position,
1451                                                 bcount);
1452         }
1453         /* Update the current position */
1454         pc->actually_transferred += bcount;
1455         pc->current_position += bcount;
1456 #if IDETAPE_DEBUG_LOG
1457         if (tape->debug_level >= 2)
1458                 printk(KERN_INFO "ide-tape: [cmd %x] transferred %d bytes "
1459                                  "on that interrupt\n", pc->c[0], bcount);
1460 #endif
1461         /* And set the interrupt handler again */
1462         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1463         return ide_started;
1464 }
1465
1466 /*
1467  *      Packet Command Interface
1468  *
1469  *      The current Packet Command is available in tape->pc, and will not
1470  *      change until we finish handling it. Each packet command is associated
1471  *      with a callback function that will be called when the command is
1472  *      finished.
1473  *
1474  *      The handling will be done in three stages:
1475  *
1476  *      1.      idetape_issue_packet_command will send the packet command to the
1477  *              drive, and will set the interrupt handler to idetape_pc_intr.
1478  *
1479  *      2.      On each interrupt, idetape_pc_intr will be called. This step
1480  *              will be repeated until the device signals us that no more
1481  *              interrupts will be issued.
1482  *
1483  *      3.      ATAPI Tape media access commands have immediate status with a
1484  *              delayed process. In case of a successful initiation of a
1485  *              media access packet command, the DSC bit will be set when the
1486  *              actual execution of the command is finished. 
1487  *              Since the tape drive will not issue an interrupt, we have to
1488  *              poll for this event. In this case, we define the request as
1489  *              "low priority request" by setting rq_status to
1490  *              IDETAPE_RQ_POSTPONED,   set a timer to poll for DSC and exit
1491  *              the driver.
1492  *
1493  *              ide.c will then give higher priority to requests which
1494  *              originate from the other device, until will change rq_status
1495  *              to RQ_ACTIVE.
1496  *
1497  *      4.      When the packet command is finished, it will be checked for errors.
1498  *
1499  *      5.      In case an error was found, we queue a request sense packet
1500  *              command in front of the request queue and retry the operation
1501  *              up to IDETAPE_MAX_PC_RETRIES times.
1502  *
1503  *      6.      In case no error was found, or we decided to give up and not
1504  *              to retry again, the callback function will be called and then
1505  *              we will handle the next request.
1506  *
1507  */
1508 static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
1509 {
1510         ide_hwif_t *hwif = drive->hwif;
1511         idetape_tape_t *tape = drive->driver_data;
1512         idetape_pc_t *pc = tape->pc;
1513         int retries = 100;
1514         ide_startstop_t startstop;
1515         u8 ireason;
1516
1517         if (ide_wait_stat(&startstop,drive,DRQ_STAT,BUSY_STAT,WAIT_READY)) {
1518                 printk(KERN_ERR "ide-tape: Strange, packet command initiated yet DRQ isn't asserted\n");
1519                 return startstop;
1520         }
1521         ireason = hwif->INB(IDE_IREASON_REG);
1522         while (retries-- && ((ireason & CD) == 0 || (ireason & IO))) {
1523                 printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while issuing "
1524                                 "a packet command, retrying\n");
1525                 udelay(100);
1526                 ireason = hwif->INB(IDE_IREASON_REG);
1527                 if (retries == 0) {
1528                         printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while "
1529                                         "issuing a packet command, ignoring\n");
1530                         ireason |= CD;
1531                         ireason &= ~IO;
1532                 }
1533         }
1534         if ((ireason & CD) == 0 || (ireason & IO)) {
1535                 printk(KERN_ERR "ide-tape: (IO,CoD) != (0,1) while issuing "
1536                                 "a packet command\n");
1537                 return ide_do_reset(drive);
1538         }
1539         /* Set the interrupt routine */
1540         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1541 #ifdef CONFIG_BLK_DEV_IDEDMA
1542         /* Begin DMA, if necessary */
1543         if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags))
1544                 hwif->dma_start(drive);
1545 #endif
1546         /* Send the actual packet */
1547         HWIF(drive)->atapi_output_bytes(drive, pc->c, 12);
1548         return ide_started;
1549 }
1550
1551 static ide_startstop_t idetape_issue_packet_command (ide_drive_t *drive, idetape_pc_t *pc)
1552 {
1553         ide_hwif_t *hwif = drive->hwif;
1554         idetape_tape_t *tape = drive->driver_data;
1555         int dma_ok = 0;
1556         u16 bcount;
1557
1558         if (tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD &&
1559             pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1560                 printk(KERN_ERR "ide-tape: possible ide-tape.c bug - "
1561                         "Two request sense in serial were issued\n");
1562         }
1563
1564         if (tape->failed_pc == NULL && pc->c[0] != IDETAPE_REQUEST_SENSE_CMD)
1565                 tape->failed_pc = pc;
1566         /* Set the current packet command */
1567         tape->pc = pc;
1568
1569         if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
1570             test_bit(PC_ABORT, &pc->flags)) {
1571                 /*
1572                  *      We will "abort" retrying a packet command in case
1573                  *      a legitimate error code was received (crossing a
1574                  *      filemark, or end of the media, for example).
1575                  */
1576                 if (!test_bit(PC_ABORT, &pc->flags)) {
1577                         if (!(pc->c[0] == IDETAPE_TEST_UNIT_READY_CMD &&
1578                               tape->sense_key == 2 && tape->asc == 4 &&
1579                              (tape->ascq == 1 || tape->ascq == 8))) {
1580                                 printk(KERN_ERR "ide-tape: %s: I/O error, "
1581                                                 "pc = %2x, key = %2x, "
1582                                                 "asc = %2x, ascq = %2x\n",
1583                                                 tape->name, pc->c[0],
1584                                                 tape->sense_key, tape->asc,
1585                                                 tape->ascq);
1586                         }
1587                         /* Giving up */
1588                         pc->error = IDETAPE_ERROR_GENERAL;
1589                 }
1590                 tape->failed_pc = NULL;
1591                 return pc->callback(drive);
1592         }
1593 #if IDETAPE_DEBUG_LOG
1594         if (tape->debug_level >= 2)
1595                 printk(KERN_INFO "ide-tape: Retry number - %d, cmd = %02X\n", pc->retries, pc->c[0]);
1596 #endif /* IDETAPE_DEBUG_LOG */
1597
1598         pc->retries++;
1599         /* We haven't transferred any data yet */
1600         pc->actually_transferred = 0;
1601         pc->current_position = pc->buffer;
1602         /* Request to transfer the entire buffer at once */
1603         bcount = pc->request_transfer;
1604
1605         if (test_and_clear_bit(PC_DMA_ERROR, &pc->flags)) {
1606                 printk(KERN_WARNING "ide-tape: DMA disabled, "
1607                                 "reverting to PIO\n");
1608                 ide_dma_off(drive);
1609         }
1610         if (test_bit(PC_DMA_RECOMMENDED, &pc->flags) && drive->using_dma)
1611                 dma_ok = !hwif->dma_setup(drive);
1612
1613         ide_pktcmd_tf_load(drive, IDE_TFLAG_NO_SELECT_MASK |
1614                            IDE_TFLAG_OUT_DEVICE, bcount, dma_ok);
1615
1616         if (dma_ok)                     /* Will begin DMA later */
1617                 set_bit(PC_DMA_IN_PROGRESS, &pc->flags);
1618         if (test_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags)) {
1619                 ide_execute_command(drive, WIN_PACKETCMD, &idetape_transfer_pc,
1620                                     IDETAPE_WAIT_CMD, NULL);
1621                 return ide_started;
1622         } else {
1623                 hwif->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
1624                 return idetape_transfer_pc(drive);
1625         }
1626 }
1627
1628 /*
1629  *      General packet command callback function.
1630  */
1631 static ide_startstop_t idetape_pc_callback (ide_drive_t *drive)
1632 {
1633         idetape_tape_t *tape = drive->driver_data;
1634         
1635 #if IDETAPE_DEBUG_LOG
1636         if (tape->debug_level >= 4)
1637                 printk(KERN_INFO "ide-tape: Reached idetape_pc_callback\n");
1638 #endif /* IDETAPE_DEBUG_LOG */
1639
1640         idetape_end_request(drive, tape->pc->error ? 0 : 1, 0);
1641         return ide_stopped;
1642 }
1643
1644 /*
1645  *      A mode sense command is used to "sense" tape parameters.
1646  */
1647 static void idetape_create_mode_sense_cmd (idetape_pc_t *pc, u8 page_code)
1648 {
1649         idetape_init_pc(pc);
1650         pc->c[0] = IDETAPE_MODE_SENSE_CMD;
1651         if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
1652                 pc->c[1] = 8;   /* DBD = 1 - Don't return block descriptors */
1653         pc->c[2] = page_code;
1654         /*
1655          * Changed pc->c[3] to 0 (255 will at best return unused info).
1656          *
1657          * For SCSI this byte is defined as subpage instead of high byte
1658          * of length and some IDE drives seem to interpret it this way
1659          * and return an error when 255 is used.
1660          */
1661         pc->c[3] = 0;
1662         pc->c[4] = 255;         /* (We will just discard data in that case) */
1663         if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
1664                 pc->request_transfer = 12;
1665         else if (page_code == IDETAPE_CAPABILITIES_PAGE)
1666                 pc->request_transfer = 24;
1667         else
1668                 pc->request_transfer = 50;
1669         pc->callback = &idetape_pc_callback;
1670 }
1671
1672 static void calculate_speeds(ide_drive_t *drive)
1673 {
1674         idetape_tape_t *tape = drive->driver_data;
1675         int full = 125, empty = 75;
1676
1677         if (time_after(jiffies, tape->controlled_pipeline_head_time + 120 * HZ)) {
1678                 tape->controlled_previous_pipeline_head = tape->controlled_last_pipeline_head;
1679                 tape->controlled_previous_head_time = tape->controlled_pipeline_head_time;
1680                 tape->controlled_last_pipeline_head = tape->pipeline_head;
1681                 tape->controlled_pipeline_head_time = jiffies;
1682         }
1683         if (time_after(jiffies, tape->controlled_pipeline_head_time + 60 * HZ))
1684                 tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_last_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_pipeline_head_time);
1685         else if (time_after(jiffies, tape->controlled_previous_head_time))
1686                 tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_previous_head_time);
1687
1688         if (tape->nr_pending_stages < tape->max_stages /*- 1 */) {
1689                 /* -1 for read mode error recovery */
1690                 if (time_after(jiffies, tape->uncontrolled_previous_head_time + 10 * HZ)) {
1691                         tape->uncontrolled_pipeline_head_time = jiffies;
1692                         tape->uncontrolled_pipeline_head_speed = (tape->pipeline_head - tape->uncontrolled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->uncontrolled_previous_head_time);
1693                 }
1694         } else {
1695                 tape->uncontrolled_previous_head_time = jiffies;
1696                 tape->uncontrolled_previous_pipeline_head = tape->pipeline_head;
1697                 if (time_after(jiffies, tape->uncontrolled_pipeline_head_time + 30 * HZ)) {
1698                         tape->uncontrolled_pipeline_head_time = jiffies;
1699                 }
1700         }
1701         tape->pipeline_head_speed = max(tape->uncontrolled_pipeline_head_speed, tape->controlled_pipeline_head_speed);
1702         if (tape->speed_control == 0) {
1703                 tape->max_insert_speed = 5000;
1704         } else if (tape->speed_control == 1) {
1705                 if (tape->nr_pending_stages >= tape->max_stages / 2)
1706                         tape->max_insert_speed = tape->pipeline_head_speed +
1707                                 (1100 - tape->pipeline_head_speed) * 2 * (tape->nr_pending_stages - tape->max_stages / 2) / tape->max_stages;
1708                 else
1709                         tape->max_insert_speed = 500 +
1710                                 (tape->pipeline_head_speed - 500) * 2 * tape->nr_pending_stages / tape->max_stages;
1711                 if (tape->nr_pending_stages >= tape->max_stages * 99 / 100)
1712                         tape->max_insert_speed = 5000;
1713         } else if (tape->speed_control == 2) {
1714                 tape->max_insert_speed = tape->pipeline_head_speed * empty / 100 +
1715                         (tape->pipeline_head_speed * full / 100 - tape->pipeline_head_speed * empty / 100) * tape->nr_pending_stages / tape->max_stages;
1716         } else
1717                 tape->max_insert_speed = tape->speed_control;
1718         tape->max_insert_speed = max(tape->max_insert_speed, 500);
1719 }
1720
1721 static ide_startstop_t idetape_media_access_finished (ide_drive_t *drive)
1722 {
1723         idetape_tape_t *tape = drive->driver_data;
1724         idetape_pc_t *pc = tape->pc;
1725         u8 stat;
1726
1727         stat = drive->hwif->INB(IDE_STATUS_REG);
1728         if (stat & SEEK_STAT) {
1729                 if (stat & ERR_STAT) {
1730                         /* Error detected */
1731                         if (pc->c[0] != IDETAPE_TEST_UNIT_READY_CMD)
1732                                 printk(KERN_ERR "ide-tape: %s: I/O error, ",
1733                                                 tape->name);
1734                         /* Retry operation */
1735                         return idetape_retry_pc(drive);
1736                 }
1737                 pc->error = 0;
1738                 if (tape->failed_pc == pc)
1739                         tape->failed_pc = NULL;
1740         } else {
1741                 pc->error = IDETAPE_ERROR_GENERAL;
1742                 tape->failed_pc = NULL;
1743         }
1744         return pc->callback(drive);
1745 }
1746
1747 static ide_startstop_t idetape_rw_callback (ide_drive_t *drive)
1748 {
1749         idetape_tape_t *tape = drive->driver_data;
1750         struct request *rq = HWGROUP(drive)->rq;
1751         int blocks = tape->pc->actually_transferred / tape->tape_block_size;
1752
1753         tape->avg_size += blocks * tape->tape_block_size;
1754         tape->insert_size += blocks * tape->tape_block_size;
1755         if (tape->insert_size > 1024 * 1024)
1756                 tape->measure_insert_time = 1;
1757         if (tape->measure_insert_time) {
1758                 tape->measure_insert_time = 0;
1759                 tape->insert_time = jiffies;
1760                 tape->insert_size = 0;
1761         }
1762         if (time_after(jiffies, tape->insert_time))
1763                 tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
1764         if (time_after_eq(jiffies, tape->avg_time + HZ)) {
1765                 tape->avg_speed = tape->avg_size * HZ / (jiffies - tape->avg_time) / 1024;
1766                 tape->avg_size = 0;
1767                 tape->avg_time = jiffies;
1768         }
1769
1770 #if IDETAPE_DEBUG_LOG   
1771         if (tape->debug_level >= 4)
1772                 printk(KERN_INFO "ide-tape: Reached idetape_rw_callback\n");
1773 #endif /* IDETAPE_DEBUG_LOG */
1774
1775         tape->first_frame_position += blocks;
1776         rq->current_nr_sectors -= blocks;
1777
1778         if (!tape->pc->error)
1779                 idetape_end_request(drive, 1, 0);
1780         else
1781                 idetape_end_request(drive, tape->pc->error, 0);
1782         return ide_stopped;
1783 }
1784
1785 static void idetape_create_read_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
1786 {
1787         idetape_init_pc(pc);
1788         pc->c[0] = IDETAPE_READ_CMD;
1789         put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
1790         pc->c[1] = 1;
1791         pc->callback = &idetape_rw_callback;
1792         pc->bh = bh;
1793         atomic_set(&bh->b_count, 0);
1794         pc->buffer = NULL;
1795         pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
1796         if (pc->request_transfer == tape->stage_size)
1797                 set_bit(PC_DMA_RECOMMENDED, &pc->flags);
1798 }
1799
1800 static void idetape_create_read_buffer_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
1801 {
1802         int size = 32768;
1803         struct idetape_bh *p = bh;
1804
1805         idetape_init_pc(pc);
1806         pc->c[0] = IDETAPE_READ_BUFFER_CMD;
1807         pc->c[1] = IDETAPE_RETRIEVE_FAULTY_BLOCK;
1808         pc->c[7] = size >> 8;
1809         pc->c[8] = size & 0xff;
1810         pc->callback = &idetape_pc_callback;
1811         pc->bh = bh;
1812         atomic_set(&bh->b_count, 0);
1813         pc->buffer = NULL;
1814         while (p) {
1815                 atomic_set(&p->b_count, 0);
1816                 p = p->b_reqnext;
1817         }
1818         pc->request_transfer = pc->buffer_size = size;
1819 }
1820
1821 static void idetape_create_write_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
1822 {
1823         idetape_init_pc(pc);
1824         pc->c[0] = IDETAPE_WRITE_CMD;
1825         put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
1826         pc->c[1] = 1;
1827         pc->callback = &idetape_rw_callback;
1828         set_bit(PC_WRITING, &pc->flags);
1829         pc->bh = bh;
1830         pc->b_data = bh->b_data;
1831         pc->b_count = atomic_read(&bh->b_count);
1832         pc->buffer = NULL;
1833         pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
1834         if (pc->request_transfer == tape->stage_size)
1835                 set_bit(PC_DMA_RECOMMENDED, &pc->flags);
1836 }
1837
1838 /*
1839  * idetape_do_request is our request handling function. 
1840  */
1841 static ide_startstop_t idetape_do_request(ide_drive_t *drive,
1842                                           struct request *rq, sector_t block)
1843 {
1844         idetape_tape_t *tape = drive->driver_data;
1845         idetape_pc_t *pc = NULL;
1846         struct request *postponed_rq = tape->postponed_rq;
1847         u8 stat;
1848
1849 #if IDETAPE_DEBUG_LOG
1850         if (tape->debug_level >= 2)
1851                 printk(KERN_INFO "ide-tape: sector: %ld, "
1852                         "nr_sectors: %ld, current_nr_sectors: %d\n",
1853                         rq->sector, rq->nr_sectors, rq->current_nr_sectors);
1854 #endif /* IDETAPE_DEBUG_LOG */
1855
1856         if (!blk_special_request(rq)) {
1857                 /*
1858                  * We do not support buffer cache originated requests.
1859                  */
1860                 printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
1861                         "request queue (%d)\n", drive->name, rq->cmd_type);
1862                 ide_end_request(drive, 0, 0);
1863                 return ide_stopped;
1864         }
1865
1866         /*
1867          *      Retry a failed packet command
1868          */
1869         if (tape->failed_pc != NULL &&
1870             tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1871                 return idetape_issue_packet_command(drive, tape->failed_pc);
1872         }
1873         if (postponed_rq != NULL)
1874                 if (rq != postponed_rq) {
1875                         printk(KERN_ERR "ide-tape: ide-tape.c bug - "
1876                                         "Two DSC requests were queued\n");
1877                         idetape_end_request(drive, 0, 0);
1878                         return ide_stopped;
1879                 }
1880
1881         tape->postponed_rq = NULL;
1882
1883         /*
1884          * If the tape is still busy, postpone our request and service
1885          * the other device meanwhile.
1886          */
1887         stat = drive->hwif->INB(IDE_STATUS_REG);
1888
1889         if (!drive->dsc_overlap && !(rq->cmd[0] & REQ_IDETAPE_PC2))
1890                 set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
1891
1892         if (drive->post_reset == 1) {
1893                 set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
1894                 drive->post_reset = 0;
1895         }
1896
1897         if (tape->tape_still_time > 100 && tape->tape_still_time < 200)
1898                 tape->measure_insert_time = 1;
1899         if (time_after(jiffies, tape->insert_time))
1900                 tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
1901         calculate_speeds(drive);
1902         if (!test_and_clear_bit(IDETAPE_IGNORE_DSC, &tape->flags) &&
1903             (stat & SEEK_STAT) == 0) {
1904                 if (postponed_rq == NULL) {
1905                         tape->dsc_polling_start = jiffies;
1906                         tape->dsc_polling_frequency = tape->best_dsc_rw_frequency;
1907                         tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
1908                 } else if (time_after(jiffies, tape->dsc_timeout)) {
1909                         printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
1910                                 tape->name);
1911                         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
1912                                 idetape_media_access_finished(drive);
1913                                 return ide_stopped;
1914                         } else {
1915                                 return ide_do_reset(drive);
1916                         }
1917                 } else if (time_after(jiffies, tape->dsc_polling_start + IDETAPE_DSC_MA_THRESHOLD))
1918                         tape->dsc_polling_frequency = IDETAPE_DSC_MA_SLOW;
1919                 idetape_postpone_request(drive);
1920                 return ide_stopped;
1921         }
1922         if (rq->cmd[0] & REQ_IDETAPE_READ) {
1923                 tape->buffer_head++;
1924                 tape->postpone_cnt = 0;
1925                 pc = idetape_next_pc_storage(drive);
1926                 idetape_create_read_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
1927                 goto out;
1928         }
1929         if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
1930                 tape->buffer_head++;
1931                 tape->postpone_cnt = 0;
1932                 pc = idetape_next_pc_storage(drive);
1933                 idetape_create_write_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
1934                 goto out;
1935         }
1936         if (rq->cmd[0] & REQ_IDETAPE_READ_BUFFER) {
1937                 tape->postpone_cnt = 0;
1938                 pc = idetape_next_pc_storage(drive);
1939                 idetape_create_read_buffer_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
1940                 goto out;
1941         }
1942         if (rq->cmd[0] & REQ_IDETAPE_PC1) {
1943                 pc = (idetape_pc_t *) rq->buffer;
1944                 rq->cmd[0] &= ~(REQ_IDETAPE_PC1);
1945                 rq->cmd[0] |= REQ_IDETAPE_PC2;
1946                 goto out;
1947         }
1948         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
1949                 idetape_media_access_finished(drive);
1950                 return ide_stopped;
1951         }
1952         BUG();
1953 out:
1954         return idetape_issue_packet_command(drive, pc);
1955 }
1956
1957 /*
1958  *      Pipeline related functions
1959  */
1960 static inline int idetape_pipeline_active (idetape_tape_t *tape)
1961 {
1962         int rc1, rc2;
1963
1964         rc1 = test_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
1965         rc2 = (tape->active_data_request != NULL);
1966         return rc1;
1967 }
1968
1969 /*
1970  *      idetape_kmalloc_stage uses __get_free_page to allocate a pipeline
1971  *      stage, along with all the necessary small buffers which together make
1972  *      a buffer of size tape->stage_size (or a bit more). We attempt to
1973  *      combine sequential pages as much as possible.
1974  *
1975  *      Returns a pointer to the new allocated stage, or NULL if we
1976  *      can't (or don't want to) allocate a stage.
1977  *
1978  *      Pipeline stages are optional and are used to increase performance.
1979  *      If we can't allocate them, we'll manage without them.
1980  */
1981 static idetape_stage_t *__idetape_kmalloc_stage (idetape_tape_t *tape, int full, int clear)
1982 {
1983         idetape_stage_t *stage;
1984         struct idetape_bh *prev_bh, *bh;
1985         int pages = tape->pages_per_stage;
1986         char *b_data = NULL;
1987
1988         if ((stage = kmalloc(sizeof (idetape_stage_t),GFP_KERNEL)) == NULL)
1989                 return NULL;
1990         stage->next = NULL;
1991
1992         bh = stage->bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
1993         if (bh == NULL)
1994                 goto abort;
1995         bh->b_reqnext = NULL;
1996         if ((bh->b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
1997                 goto abort;
1998         if (clear)
1999                 memset(bh->b_data, 0, PAGE_SIZE);
2000         bh->b_size = PAGE_SIZE;
2001         atomic_set(&bh->b_count, full ? bh->b_size : 0);
2002
2003         while (--pages) {
2004                 if ((b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2005                         goto abort;
2006                 if (clear)
2007                         memset(b_data, 0, PAGE_SIZE);
2008                 if (bh->b_data == b_data + PAGE_SIZE) {
2009                         bh->b_size += PAGE_SIZE;
2010                         bh->b_data -= PAGE_SIZE;
2011                         if (full)
2012                                 atomic_add(PAGE_SIZE, &bh->b_count);
2013                         continue;
2014                 }
2015                 if (b_data == bh->b_data + bh->b_size) {
2016                         bh->b_size += PAGE_SIZE;
2017                         if (full)
2018                                 atomic_add(PAGE_SIZE, &bh->b_count);
2019                         continue;
2020                 }
2021                 prev_bh = bh;
2022                 if ((bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL)) == NULL) {
2023                         free_page((unsigned long) b_data);
2024                         goto abort;
2025                 }
2026                 bh->b_reqnext = NULL;
2027                 bh->b_data = b_data;
2028                 bh->b_size = PAGE_SIZE;
2029                 atomic_set(&bh->b_count, full ? bh->b_size : 0);
2030                 prev_bh->b_reqnext = bh;
2031         }
2032         bh->b_size -= tape->excess_bh_size;
2033         if (full)
2034                 atomic_sub(tape->excess_bh_size, &bh->b_count);
2035         return stage;
2036 abort:
2037         __idetape_kfree_stage(stage);
2038         return NULL;
2039 }
2040
2041 static idetape_stage_t *idetape_kmalloc_stage (idetape_tape_t *tape)
2042 {
2043         idetape_stage_t *cache_stage = tape->cache_stage;
2044
2045 #if IDETAPE_DEBUG_LOG
2046         if (tape->debug_level >= 4)
2047                 printk(KERN_INFO "ide-tape: Reached idetape_kmalloc_stage\n");
2048 #endif /* IDETAPE_DEBUG_LOG */
2049
2050         if (tape->nr_stages >= tape->max_stages)
2051                 return NULL;
2052         if (cache_stage != NULL) {
2053                 tape->cache_stage = NULL;
2054                 return cache_stage;
2055         }
2056         return __idetape_kmalloc_stage(tape, 0, 0);
2057 }
2058
2059 static int idetape_copy_stage_from_user (idetape_tape_t *tape, idetape_stage_t *stage, const char __user *buf, int n)
2060 {
2061         struct idetape_bh *bh = tape->bh;
2062         int count;
2063         int ret = 0;
2064
2065         while (n) {
2066                 if (bh == NULL) {
2067                         printk(KERN_ERR "ide-tape: bh == NULL in "
2068                                 "idetape_copy_stage_from_user\n");
2069                         return 1;
2070                 }
2071                 count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), (unsigned int)n);
2072                 if (copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf, count))
2073                         ret = 1;
2074                 n -= count;
2075                 atomic_add(count, &bh->b_count);
2076                 buf += count;
2077                 if (atomic_read(&bh->b_count) == bh->b_size) {
2078                         bh = bh->b_reqnext;
2079                         if (bh)
2080                                 atomic_set(&bh->b_count, 0);
2081                 }
2082         }
2083         tape->bh = bh;
2084         return ret;
2085 }
2086
2087 static int idetape_copy_stage_to_user (idetape_tape_t *tape, char __user *buf, idetape_stage_t *stage, int n)
2088 {
2089         struct idetape_bh *bh = tape->bh;
2090         int count;
2091         int ret = 0;
2092
2093         while (n) {
2094                 if (bh == NULL) {
2095                         printk(KERN_ERR "ide-tape: bh == NULL in "
2096                                 "idetape_copy_stage_to_user\n");
2097                         return 1;
2098                 }
2099                 count = min(tape->b_count, n);
2100                 if  (copy_to_user(buf, tape->b_data, count))
2101                         ret = 1;
2102                 n -= count;
2103                 tape->b_data += count;
2104                 tape->b_count -= count;
2105                 buf += count;
2106                 if (!tape->b_count) {
2107                         tape->bh = bh = bh->b_reqnext;
2108                         if (bh) {
2109                                 tape->b_data = bh->b_data;
2110                                 tape->b_count = atomic_read(&bh->b_count);
2111                         }
2112                 }
2113         }
2114         return ret;
2115 }
2116
2117 static void idetape_init_merge_stage (idetape_tape_t *tape)
2118 {
2119         struct idetape_bh *bh = tape->merge_stage->bh;
2120         
2121         tape->bh = bh;
2122         if (tape->chrdev_direction == idetape_direction_write)
2123                 atomic_set(&bh->b_count, 0);
2124         else {
2125                 tape->b_data = bh->b_data;
2126                 tape->b_count = atomic_read(&bh->b_count);
2127         }
2128 }
2129
2130 static void idetape_switch_buffers (idetape_tape_t *tape, idetape_stage_t *stage)
2131 {
2132         struct idetape_bh *tmp;
2133
2134         tmp = stage->bh;
2135         stage->bh = tape->merge_stage->bh;
2136         tape->merge_stage->bh = tmp;
2137         idetape_init_merge_stage(tape);
2138 }
2139
2140 /*
2141  *      idetape_add_stage_tail adds a new stage at the end of the pipeline.
2142  */
2143 static void idetape_add_stage_tail (ide_drive_t *drive,idetape_stage_t *stage)
2144 {
2145         idetape_tape_t *tape = drive->driver_data;
2146         unsigned long flags;
2147         
2148 #if IDETAPE_DEBUG_LOG
2149         if (tape->debug_level >= 4)
2150                 printk (KERN_INFO "ide-tape: Reached idetape_add_stage_tail\n");
2151 #endif /* IDETAPE_DEBUG_LOG */
2152         spin_lock_irqsave(&tape->spinlock, flags);
2153         stage->next = NULL;
2154         if (tape->last_stage != NULL)
2155                 tape->last_stage->next=stage;
2156         else
2157                 tape->first_stage = tape->next_stage=stage;
2158         tape->last_stage = stage;
2159         if (tape->next_stage == NULL)
2160                 tape->next_stage = tape->last_stage;
2161         tape->nr_stages++;
2162         tape->nr_pending_stages++;
2163         spin_unlock_irqrestore(&tape->spinlock, flags);
2164 }
2165
2166 /*
2167  *      idetape_wait_for_request installs a completion in a pending request
2168  *      and sleeps until it is serviced.
2169  *
2170  *      The caller should ensure that the request will not be serviced
2171  *      before we install the completion (usually by disabling interrupts).
2172  */
2173 static void idetape_wait_for_request (ide_drive_t *drive, struct request *rq)
2174 {
2175         DECLARE_COMPLETION_ONSTACK(wait);
2176         idetape_tape_t *tape = drive->driver_data;
2177
2178         if (rq == NULL || !blk_special_request(rq)) {
2179                 printk (KERN_ERR "ide-tape: bug: Trying to sleep on non-valid request\n");
2180                 return;
2181         }
2182         rq->end_io_data = &wait;
2183         rq->end_io = blk_end_sync_rq;
2184         spin_unlock_irq(&tape->spinlock);
2185         wait_for_completion(&wait);
2186         /* The stage and its struct request have been deallocated */
2187         spin_lock_irq(&tape->spinlock);
2188 }
2189
2190 static ide_startstop_t idetape_read_position_callback (ide_drive_t *drive)
2191 {
2192         idetape_tape_t *tape = drive->driver_data;
2193         idetape_read_position_result_t *result;
2194         
2195 #if IDETAPE_DEBUG_LOG
2196         if (tape->debug_level >= 4)
2197                 printk(KERN_INFO "ide-tape: Reached idetape_read_position_callback\n");
2198 #endif /* IDETAPE_DEBUG_LOG */
2199
2200         if (!tape->pc->error) {
2201                 result = (idetape_read_position_result_t *) tape->pc->buffer;
2202 #if IDETAPE_DEBUG_LOG
2203                 if (tape->debug_level >= 2)
2204                         printk(KERN_INFO "ide-tape: BOP - %s\n",result->bop ? "Yes":"No");
2205                 if (tape->debug_level >= 2)
2206                         printk(KERN_INFO "ide-tape: EOP - %s\n",result->eop ? "Yes":"No");
2207 #endif /* IDETAPE_DEBUG_LOG */
2208                 if (result->bpu) {
2209                         printk(KERN_INFO "ide-tape: Block location is unknown to the tape\n");
2210                         clear_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2211                         idetape_end_request(drive, 0, 0);
2212                 } else {
2213 #if IDETAPE_DEBUG_LOG
2214                         if (tape->debug_level >= 2)
2215                                 printk(KERN_INFO "ide-tape: Block Location - %u\n", ntohl(result->first_block));
2216 #endif /* IDETAPE_DEBUG_LOG */
2217                         tape->partition = result->partition;
2218                         tape->first_frame_position = ntohl(result->first_block);
2219                         tape->last_frame_position = ntohl(result->last_block);
2220                         tape->blocks_in_buffer = result->blocks_in_buffer[2];
2221                         set_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2222                         idetape_end_request(drive, 1, 0);
2223                 }
2224         } else {
2225                 idetape_end_request(drive, 0, 0);
2226         }
2227         return ide_stopped;
2228 }
2229
2230 /*
2231  *      idetape_create_write_filemark_cmd will:
2232  *
2233  *              1.      Write a filemark if write_filemark=1.
2234  *              2.      Flush the device buffers without writing a filemark
2235  *                      if write_filemark=0.
2236  *
2237  */
2238 static void idetape_create_write_filemark_cmd (ide_drive_t *drive, idetape_pc_t *pc,int write_filemark)
2239 {
2240         idetape_init_pc(pc);
2241         pc->c[0] = IDETAPE_WRITE_FILEMARK_CMD;
2242         pc->c[4] = write_filemark;
2243         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2244         pc->callback = &idetape_pc_callback;
2245 }
2246
2247 static void idetape_create_test_unit_ready_cmd(idetape_pc_t *pc)
2248 {
2249         idetape_init_pc(pc);
2250         pc->c[0] = IDETAPE_TEST_UNIT_READY_CMD;
2251         pc->callback = &idetape_pc_callback;
2252 }
2253
2254 /*
2255  *      idetape_queue_pc_tail is based on the following functions:
2256  *
2257  *      ide_do_drive_cmd from ide.c
2258  *      cdrom_queue_request and cdrom_queue_packet_command from ide-cd.c
2259  *
2260  *      We add a special packet command request to the tail of the request
2261  *      queue, and wait for it to be serviced.
2262  *
2263  *      This is not to be called from within the request handling part
2264  *      of the driver ! We allocate here data in the stack, and it is valid
2265  *      until the request is finished. This is not the case for the bottom
2266  *      part of the driver, where we are always leaving the functions to wait
2267  *      for an interrupt or a timer event.
2268  *
2269  *      From the bottom part of the driver, we should allocate safe memory
2270  *      using idetape_next_pc_storage and idetape_next_rq_storage, and add
2271  *      the request to the request list without waiting for it to be serviced !
2272  *      In that case, we usually use idetape_queue_pc_head.
2273  */
2274 static int __idetape_queue_pc_tail (ide_drive_t *drive, idetape_pc_t *pc)
2275 {
2276         struct ide_tape_obj *tape = drive->driver_data;
2277         struct request rq;
2278
2279         idetape_init_rq(&rq, REQ_IDETAPE_PC1);
2280         rq.buffer = (char *) pc;
2281         rq.rq_disk = tape->disk;
2282         return ide_do_drive_cmd(drive, &rq, ide_wait);
2283 }
2284
2285 static void idetape_create_load_unload_cmd (ide_drive_t *drive, idetape_pc_t *pc,int cmd)
2286 {
2287         idetape_init_pc(pc);
2288         pc->c[0] = IDETAPE_LOAD_UNLOAD_CMD;
2289         pc->c[4] = cmd;
2290         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2291         pc->callback = &idetape_pc_callback;
2292 }
2293
2294 static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
2295 {
2296         idetape_tape_t *tape = drive->driver_data;
2297         idetape_pc_t pc;
2298         int load_attempted = 0;
2299
2300         /*
2301          * Wait for the tape to become ready
2302          */
2303         set_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags);
2304         timeout += jiffies;
2305         while (time_before(jiffies, timeout)) {
2306                 idetape_create_test_unit_ready_cmd(&pc);
2307                 if (!__idetape_queue_pc_tail(drive, &pc))
2308                         return 0;
2309                 if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
2310                     || (tape->asc == 0x3A)) {   /* no media */
2311                         if (load_attempted)
2312                                 return -ENOMEDIUM;
2313                         idetape_create_load_unload_cmd(drive, &pc, IDETAPE_LU_LOAD_MASK);
2314                         __idetape_queue_pc_tail(drive, &pc);
2315                         load_attempted = 1;
2316                 /* not about to be ready */
2317                 } else if (!(tape->sense_key == 2 && tape->asc == 4 &&
2318                              (tape->ascq == 1 || tape->ascq == 8)))
2319                         return -EIO;
2320                 msleep(100);
2321         }
2322         return -EIO;
2323 }
2324
2325 static int idetape_queue_pc_tail (ide_drive_t *drive,idetape_pc_t *pc)
2326 {
2327         return __idetape_queue_pc_tail(drive, pc);
2328 }
2329
2330 static int idetape_flush_tape_buffers (ide_drive_t *drive)
2331 {
2332         idetape_pc_t pc;
2333         int rc;
2334
2335         idetape_create_write_filemark_cmd(drive, &pc, 0);
2336         if ((rc = idetape_queue_pc_tail(drive, &pc)))
2337                 return rc;
2338         idetape_wait_ready(drive, 60 * 5 * HZ);
2339         return 0;
2340 }
2341
2342 static void idetape_create_read_position_cmd (idetape_pc_t *pc)
2343 {
2344         idetape_init_pc(pc);
2345         pc->c[0] = IDETAPE_READ_POSITION_CMD;
2346         pc->request_transfer = 20;
2347         pc->callback = &idetape_read_position_callback;
2348 }
2349
2350 static int idetape_read_position (ide_drive_t *drive)
2351 {
2352         idetape_tape_t *tape = drive->driver_data;
2353         idetape_pc_t pc;
2354         int position;
2355
2356 #if IDETAPE_DEBUG_LOG
2357         if (tape->debug_level >= 4)
2358                 printk(KERN_INFO "ide-tape: Reached idetape_read_position\n");
2359 #endif /* IDETAPE_DEBUG_LOG */
2360
2361         idetape_create_read_position_cmd(&pc);
2362         if (idetape_queue_pc_tail(drive, &pc))
2363                 return -1;
2364         position = tape->first_frame_position;
2365         return position;
2366 }
2367
2368 static void idetape_create_locate_cmd (ide_drive_t *drive, idetape_pc_t *pc, unsigned int block, u8 partition, int skip)
2369 {
2370         idetape_init_pc(pc);
2371         pc->c[0] = IDETAPE_LOCATE_CMD;
2372         pc->c[1] = 2;
2373         put_unaligned(htonl(block), (unsigned int *) &pc->c[3]);
2374         pc->c[8] = partition;
2375         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2376         pc->callback = &idetape_pc_callback;
2377 }
2378
2379 static int idetape_create_prevent_cmd (ide_drive_t *drive, idetape_pc_t *pc, int prevent)
2380 {
2381         idetape_tape_t *tape = drive->driver_data;
2382
2383         /* device supports locking according to capabilities page */
2384         if (!(tape->caps[6] & 0x01))
2385                 return 0;
2386
2387         idetape_init_pc(pc);
2388         pc->c[0] = IDETAPE_PREVENT_CMD;
2389         pc->c[4] = prevent;
2390         pc->callback = &idetape_pc_callback;
2391         return 1;
2392 }
2393
2394 static int __idetape_discard_read_pipeline (ide_drive_t *drive)
2395 {
2396         idetape_tape_t *tape = drive->driver_data;
2397         unsigned long flags;
2398         int cnt;
2399
2400         if (tape->chrdev_direction != idetape_direction_read)
2401                 return 0;
2402
2403         /* Remove merge stage. */
2404         cnt = tape->merge_stage_size / tape->tape_block_size;
2405         if (test_and_clear_bit(IDETAPE_FILEMARK, &tape->flags))
2406                 ++cnt;          /* Filemarks count as 1 sector */
2407         tape->merge_stage_size = 0;
2408         if (tape->merge_stage != NULL) {
2409                 __idetape_kfree_stage(tape->merge_stage);
2410                 tape->merge_stage = NULL;
2411         }
2412
2413         /* Clear pipeline flags. */
2414         clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
2415         tape->chrdev_direction = idetape_direction_none;
2416
2417         /* Remove pipeline stages. */
2418         if (tape->first_stage == NULL)
2419                 return 0;
2420
2421         spin_lock_irqsave(&tape->spinlock, flags);
2422         tape->next_stage = NULL;
2423         if (idetape_pipeline_active(tape))
2424                 idetape_wait_for_request(drive, tape->active_data_request);
2425         spin_unlock_irqrestore(&tape->spinlock, flags);
2426
2427         while (tape->first_stage != NULL) {
2428                 struct request *rq_ptr = &tape->first_stage->rq;
2429
2430                 cnt += rq_ptr->nr_sectors - rq_ptr->current_nr_sectors; 
2431                 if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
2432                         ++cnt;
2433                 idetape_remove_stage_head(drive);
2434         }
2435         tape->nr_pending_stages = 0;
2436         tape->max_stages = tape->min_pipeline;
2437         return cnt;
2438 }
2439
2440 /*
2441  *      idetape_position_tape positions the tape to the requested block
2442  *      using the LOCATE packet command. A READ POSITION command is then
2443  *      issued to check where we are positioned.
2444  *
2445  *      Like all higher level operations, we queue the commands at the tail
2446  *      of the request queue and wait for their completion.
2447  *      
2448  */
2449 static int idetape_position_tape (ide_drive_t *drive, unsigned int block, u8 partition, int skip)
2450 {
2451         idetape_tape_t *tape = drive->driver_data;
2452         int retval;
2453         idetape_pc_t pc;
2454
2455         if (tape->chrdev_direction == idetape_direction_read)
2456                 __idetape_discard_read_pipeline(drive);
2457         idetape_wait_ready(drive, 60 * 5 * HZ);
2458         idetape_create_locate_cmd(drive, &pc, block, partition, skip);
2459         retval = idetape_queue_pc_tail(drive, &pc);
2460         if (retval)
2461                 return (retval);
2462
2463         idetape_create_read_position_cmd(&pc);
2464         return (idetape_queue_pc_tail(drive, &pc));
2465 }
2466
2467 static void idetape_discard_read_pipeline (ide_drive_t *drive, int restore_position)
2468 {
2469         idetape_tape_t *tape = drive->driver_data;
2470         int cnt;
2471         int seek, position;
2472
2473         cnt = __idetape_discard_read_pipeline(drive);
2474         if (restore_position) {
2475                 position = idetape_read_position(drive);
2476                 seek = position > cnt ? position - cnt : 0;
2477                 if (idetape_position_tape(drive, seek, 0, 0)) {
2478                         printk(KERN_INFO "ide-tape: %s: position_tape failed in discard_pipeline()\n", tape->name);
2479                         return;
2480                 }
2481         }
2482 }
2483
2484 /*
2485  * idetape_queue_rw_tail generates a read/write request for the block
2486  * device interface and wait for it to be serviced.
2487  */
2488 static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks, struct idetape_bh *bh)
2489 {
2490         idetape_tape_t *tape = drive->driver_data;
2491         struct request rq;
2492
2493 #if IDETAPE_DEBUG_LOG
2494         if (tape->debug_level >= 2)
2495                 printk(KERN_INFO "ide-tape: idetape_queue_rw_tail: cmd=%d\n",cmd);
2496 #endif /* IDETAPE_DEBUG_LOG */
2497         if (idetape_pipeline_active(tape)) {
2498                 printk(KERN_ERR "ide-tape: bug: the pipeline is active in idetape_queue_rw_tail\n");
2499                 return (0);
2500         }
2501
2502         idetape_init_rq(&rq, cmd);
2503         rq.rq_disk = tape->disk;
2504         rq.special = (void *)bh;
2505         rq.sector = tape->first_frame_position;
2506         rq.nr_sectors = rq.current_nr_sectors = blocks;
2507         (void) ide_do_drive_cmd(drive, &rq, ide_wait);
2508
2509         if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
2510                 return 0;
2511
2512         if (tape->merge_stage)
2513                 idetape_init_merge_stage(tape);
2514         if (rq.errors == IDETAPE_ERROR_GENERAL)
2515                 return -EIO;
2516         return (tape->tape_block_size * (blocks-rq.current_nr_sectors));
2517 }
2518
2519 /*
2520  *      idetape_insert_pipeline_into_queue is used to start servicing the
2521  *      pipeline stages, starting from tape->next_stage.
2522  */
2523 static void idetape_insert_pipeline_into_queue (ide_drive_t *drive)
2524 {
2525         idetape_tape_t *tape = drive->driver_data;
2526
2527         if (tape->next_stage == NULL)
2528                 return;
2529         if (!idetape_pipeline_active(tape)) {
2530                 set_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
2531                 idetape_active_next_stage(drive);
2532                 (void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
2533         }
2534 }
2535
2536 static void idetape_create_inquiry_cmd (idetape_pc_t *pc)
2537 {
2538         idetape_init_pc(pc);
2539         pc->c[0] = IDETAPE_INQUIRY_CMD;
2540         pc->c[4] = pc->request_transfer = 254;
2541         pc->callback = &idetape_pc_callback;
2542 }
2543
2544 static void idetape_create_rewind_cmd (ide_drive_t *drive, idetape_pc_t *pc)
2545 {
2546         idetape_init_pc(pc);
2547         pc->c[0] = IDETAPE_REWIND_CMD;
2548         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2549         pc->callback = &idetape_pc_callback;
2550 }
2551
2552 static void idetape_create_erase_cmd (idetape_pc_t *pc)
2553 {
2554         idetape_init_pc(pc);
2555         pc->c[0] = IDETAPE_ERASE_CMD;
2556         pc->c[1] = 1;
2557         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2558         pc->callback = &idetape_pc_callback;
2559 }
2560
2561 static void idetape_create_space_cmd (idetape_pc_t *pc,int count, u8 cmd)
2562 {
2563         idetape_init_pc(pc);
2564         pc->c[0] = IDETAPE_SPACE_CMD;
2565         put_unaligned(htonl(count), (unsigned int *) &pc->c[1]);
2566         pc->c[1] = cmd;
2567         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2568         pc->callback = &idetape_pc_callback;
2569 }
2570
2571 static void idetape_wait_first_stage (ide_drive_t *drive)
2572 {
2573         idetape_tape_t *tape = drive->driver_data;
2574         unsigned long flags;
2575
2576         if (tape->first_stage == NULL)
2577                 return;
2578         spin_lock_irqsave(&tape->spinlock, flags);
2579         if (tape->active_stage == tape->first_stage)
2580                 idetape_wait_for_request(drive, tape->active_data_request);
2581         spin_unlock_irqrestore(&tape->spinlock, flags);
2582 }
2583
2584 /*
2585  *      idetape_add_chrdev_write_request tries to add a character device
2586  *      originated write request to our pipeline. In case we don't succeed,
2587  *      we revert to non-pipelined operation mode for this request.
2588  *
2589  *      1.      Try to allocate a new pipeline stage.
2590  *      2.      If we can't, wait for more and more requests to be serviced
2591  *              and try again each time.
2592  *      3.      If we still can't allocate a stage, fallback to
2593  *              non-pipelined operation mode for this request.
2594  */
2595 static int idetape_add_chrdev_write_request (ide_drive_t *drive, int blocks)
2596 {
2597         idetape_tape_t *tape = drive->driver_data;
2598         idetape_stage_t *new_stage;
2599         unsigned long flags;
2600         struct request *rq;
2601
2602 #if IDETAPE_DEBUG_LOG
2603         if (tape->debug_level >= 3)
2604                 printk(KERN_INFO "ide-tape: Reached idetape_add_chrdev_write_request\n");
2605 #endif /* IDETAPE_DEBUG_LOG */
2606
2607         /*
2608          *      Attempt to allocate a new stage.
2609          *      Pay special attention to possible race conditions.
2610          */
2611         while ((new_stage = idetape_kmalloc_stage(tape)) == NULL) {
2612                 spin_lock_irqsave(&tape->spinlock, flags);
2613                 if (idetape_pipeline_active(tape)) {
2614                         idetape_wait_for_request(drive, tape->active_data_request);
2615                         spin_unlock_irqrestore(&tape->spinlock, flags);
2616                 } else {
2617                         spin_unlock_irqrestore(&tape->spinlock, flags);
2618                         idetape_insert_pipeline_into_queue(drive);
2619                         if (idetape_pipeline_active(tape))
2620                                 continue;
2621                         /*
2622                          *      Linux is short on memory. Fallback to
2623                          *      non-pipelined operation mode for this request.
2624                          */
2625                         return idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks, tape->merge_stage->bh);
2626                 }
2627         }
2628         rq = &new_stage->rq;
2629         idetape_init_rq(rq, REQ_IDETAPE_WRITE);
2630         /* Doesn't actually matter - We always assume sequential access */
2631         rq->sector = tape->first_frame_position;
2632         rq->nr_sectors = rq->current_nr_sectors = blocks;
2633
2634         idetape_switch_buffers(tape, new_stage);
2635         idetape_add_stage_tail(drive, new_stage);
2636         tape->pipeline_head++;
2637         calculate_speeds(drive);
2638
2639         /*
2640          *      Estimate whether the tape has stopped writing by checking
2641          *      if our write pipeline is currently empty. If we are not
2642          *      writing anymore, wait for the pipeline to be full enough
2643          *      (90%) before starting to service requests, so that we will
2644          *      be able to keep up with the higher speeds of the tape.
2645          */
2646         if (!idetape_pipeline_active(tape)) {
2647                 if (tape->nr_stages >= tape->max_stages * 9 / 10 ||
2648                     tape->nr_stages >= tape->max_stages - tape->uncontrolled_pipeline_head_speed * 3 * 1024 / tape->tape_block_size) {
2649                         tape->measure_insert_time = 1;
2650                         tape->insert_time = jiffies;
2651                         tape->insert_size = 0;
2652                         tape->insert_speed = 0;
2653                         idetape_insert_pipeline_into_queue(drive);
2654                 }
2655         }
2656         if (test_and_clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags))
2657                 /* Return a deferred error */
2658                 return -EIO;
2659         return blocks;
2660 }
2661
2662 /*
2663  *      idetape_wait_for_pipeline will wait until all pending pipeline
2664  *      requests are serviced. Typically called on device close.
2665  */
2666 static void idetape_wait_for_pipeline (ide_drive_t *drive)
2667 {
2668         idetape_tape_t *tape = drive->driver_data;
2669         unsigned long flags;
2670
2671         while (tape->next_stage || idetape_pipeline_active(tape)) {
2672                 idetape_insert_pipeline_into_queue(drive);
2673                 spin_lock_irqsave(&tape->spinlock, flags);
2674                 if (idetape_pipeline_active(tape))
2675                         idetape_wait_for_request(drive, tape->active_data_request);
2676                 spin_unlock_irqrestore(&tape->spinlock, flags);
2677         }
2678 }
2679
2680 static void idetape_empty_write_pipeline (ide_drive_t *drive)
2681 {
2682         idetape_tape_t *tape = drive->driver_data;
2683         int blocks, min;
2684         struct idetape_bh *bh;
2685
2686         if (tape->chrdev_direction != idetape_direction_write) {
2687                 printk(KERN_ERR "ide-tape: bug: Trying to empty write pipeline, but we are not writing.\n");
2688                 return;
2689         }
2690         if (tape->merge_stage_size > tape->stage_size) {
2691                 printk(KERN_ERR "ide-tape: bug: merge_buffer too big\n");
2692                 tape->merge_stage_size = tape->stage_size;
2693         }
2694         if (tape->merge_stage_size) {
2695                 blocks = tape->merge_stage_size / tape->tape_block_size;
2696                 if (tape->merge_stage_size % tape->tape_block_size) {
2697                         unsigned int i;
2698
2699                         blocks++;
2700                         i = tape->tape_block_size - tape->merge_stage_size % tape->tape_block_size;
2701                         bh = tape->bh->b_reqnext;
2702                         while (bh) {
2703                                 atomic_set(&bh->b_count, 0);
2704                                 bh = bh->b_reqnext;
2705                         }
2706                         bh = tape->bh;
2707                         while (i) {
2708                                 if (bh == NULL) {
2709
2710                                         printk(KERN_INFO "ide-tape: bug, bh NULL\n");
2711                                         break;
2712                                 }
2713                                 min = min(i, (unsigned int)(bh->b_size - atomic_read(&bh->b_count)));
2714                                 memset(bh->b_data + atomic_read(&bh->b_count), 0, min);
2715                                 atomic_add(min, &bh->b_count);
2716                                 i -= min;
2717                                 bh = bh->b_reqnext;
2718                         }
2719                 }
2720                 (void) idetape_add_chrdev_write_request(drive, blocks);
2721                 tape->merge_stage_size = 0;
2722         }
2723         idetape_wait_for_pipeline(drive);
2724         if (tape->merge_stage != NULL) {
2725                 __idetape_kfree_stage(tape->merge_stage);
2726                 tape->merge_stage = NULL;
2727         }
2728         clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
2729         tape->chrdev_direction = idetape_direction_none;
2730
2731         /*
2732          *      On the next backup, perform the feedback loop again.
2733          *      (I don't want to keep sense information between backups,
2734          *       as some systems are constantly on, and the system load
2735          *       can be totally different on the next backup).
2736          */
2737         tape->max_stages = tape->min_pipeline;
2738         if (tape->first_stage != NULL ||
2739             tape->next_stage != NULL ||
2740             tape->last_stage != NULL ||
2741             tape->nr_stages != 0) {
2742                 printk(KERN_ERR "ide-tape: ide-tape pipeline bug, "
2743                         "first_stage %p, next_stage %p, "
2744                         "last_stage %p, nr_stages %d\n",
2745                         tape->first_stage, tape->next_stage,
2746                         tape->last_stage, tape->nr_stages);
2747         }
2748 }
2749
2750 static void idetape_restart_speed_control (ide_drive_t *drive)
2751 {
2752         idetape_tape_t *tape = drive->driver_data;
2753
2754         tape->restart_speed_control_req = 0;
2755         tape->pipeline_head = 0;
2756         tape->controlled_last_pipeline_head = tape->uncontrolled_last_pipeline_head = 0;
2757         tape->controlled_previous_pipeline_head = tape->uncontrolled_previous_pipeline_head = 0;
2758         tape->pipeline_head_speed = tape->controlled_pipeline_head_speed = 5000;
2759         tape->uncontrolled_pipeline_head_speed = 0;
2760         tape->controlled_pipeline_head_time = tape->uncontrolled_pipeline_head_time = jiffies;
2761         tape->controlled_previous_head_time = tape->uncontrolled_previous_head_time = jiffies;
2762 }
2763
2764 static int idetape_initiate_read (ide_drive_t *drive, int max_stages)
2765 {
2766         idetape_tape_t *tape = drive->driver_data;
2767         idetape_stage_t *new_stage;
2768         struct request rq;
2769         int bytes_read;
2770         u16 blocks = *(u16 *)&tape->caps[12];
2771
2772         /* Initialize read operation */
2773         if (tape->chrdev_direction != idetape_direction_read) {
2774                 if (tape->chrdev_direction == idetape_direction_write) {
2775                         idetape_empty_write_pipeline(drive);
2776                         idetape_flush_tape_buffers(drive);
2777                 }
2778                 if (tape->merge_stage || tape->merge_stage_size) {
2779                         printk (KERN_ERR "ide-tape: merge_stage_size should be 0 now\n");
2780                         tape->merge_stage_size = 0;
2781                 }
2782                 if ((tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0)) == NULL)
2783                         return -ENOMEM;
2784                 tape->chrdev_direction = idetape_direction_read;
2785
2786                 /*
2787                  *      Issue a read 0 command to ensure that DSC handshake
2788                  *      is switched from completion mode to buffer available
2789                  *      mode.
2790                  *      No point in issuing this if DSC overlap isn't supported,
2791                  *      some drives (Seagate STT3401A) will return an error.
2792                  */
2793                 if (drive->dsc_overlap) {
2794                         bytes_read = idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, 0, tape->merge_stage->bh);
2795                         if (bytes_read < 0) {
2796                                 __idetape_kfree_stage(tape->merge_stage);
2797                                 tape->merge_stage = NULL;
2798                                 tape->chrdev_direction = idetape_direction_none;
2799                                 return bytes_read;
2800                         }
2801                 }
2802         }
2803         if (tape->restart_speed_control_req)
2804                 idetape_restart_speed_control(drive);
2805         idetape_init_rq(&rq, REQ_IDETAPE_READ);
2806         rq.sector = tape->first_frame_position;
2807         rq.nr_sectors = rq.current_nr_sectors = blocks;
2808         if (!test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags) &&
2809             tape->nr_stages < max_stages) {
2810                 new_stage = idetape_kmalloc_stage(tape);
2811                 while (new_stage != NULL) {
2812                         new_stage->rq = rq;
2813                         idetape_add_stage_tail(drive, new_stage);
2814                         if (tape->nr_stages >= max_stages)
2815                                 break;
2816                         new_stage = idetape_kmalloc_stage(tape);
2817                 }
2818         }
2819         if (!idetape_pipeline_active(tape)) {
2820                 if (tape->nr_pending_stages >= 3 * max_stages / 4) {
2821                         tape->measure_insert_time = 1;
2822                         tape->insert_time = jiffies;
2823                         tape->insert_size = 0;
2824                         tape->insert_speed = 0;
2825                         idetape_insert_pipeline_into_queue(drive);
2826                 }
2827         }
2828         return 0;
2829 }
2830
2831 /*
2832  *      idetape_add_chrdev_read_request is called from idetape_chrdev_read
2833  *      to service a character device read request and add read-ahead
2834  *      requests to our pipeline.
2835  */
2836 static int idetape_add_chrdev_read_request (ide_drive_t *drive,int blocks)
2837 {
2838         idetape_tape_t *tape = drive->driver_data;
2839         unsigned long flags;
2840         struct request *rq_ptr;
2841         int bytes_read;
2842
2843 #if IDETAPE_DEBUG_LOG
2844         if (tape->debug_level >= 4)
2845                 printk(KERN_INFO "ide-tape: Reached idetape_add_chrdev_read_request, %d blocks\n", blocks);
2846 #endif /* IDETAPE_DEBUG_LOG */
2847
2848         /*
2849          * If we are at a filemark, return a read length of 0
2850          */
2851         if (test_bit(IDETAPE_FILEMARK, &tape->flags))
2852                 return 0;
2853
2854         /*
2855          * Wait for the next block to be available at the head
2856          * of the pipeline
2857          */
2858         idetape_initiate_read(drive, tape->max_stages);
2859         if (tape->first_stage == NULL) {
2860                 if (test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags))
2861                         return 0;
2862                 return idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, blocks, tape->merge_stage->bh);
2863         }
2864         idetape_wait_first_stage(drive);
2865         rq_ptr = &tape->first_stage->rq;
2866         bytes_read = tape->tape_block_size * (rq_ptr->nr_sectors - rq_ptr->current_nr_sectors);
2867         rq_ptr->nr_sectors = rq_ptr->current_nr_sectors = 0;
2868
2869
2870         if (rq_ptr->errors == IDETAPE_ERROR_EOD)
2871                 return 0;
2872         else {
2873                 idetape_switch_buffers(tape, tape->first_stage);
2874                 if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
2875                         set_bit(IDETAPE_FILEMARK, &tape->flags);
2876                 spin_lock_irqsave(&tape->spinlock, flags);
2877                 idetape_remove_stage_head(drive);
2878                 spin_unlock_irqrestore(&tape->spinlock, flags);
2879                 tape->pipeline_head++;
2880                 calculate_speeds(drive);
2881         }
2882         if (bytes_read > blocks * tape->tape_block_size) {
2883                 printk(KERN_ERR "ide-tape: bug: trying to return more bytes than requested\n");
2884                 bytes_read = blocks * tape->tape_block_size;
2885         }
2886         return (bytes_read);
2887 }
2888
2889 static void idetape_pad_zeros (ide_drive_t *drive, int bcount)
2890 {
2891         idetape_tape_t *tape = drive->driver_data;
2892         struct idetape_bh *bh;
2893         int blocks;
2894         
2895         while (bcount) {
2896                 unsigned int count;
2897
2898                 bh = tape->merge_stage->bh;
2899                 count = min(tape->stage_size, bcount);
2900                 bcount -= count;
2901                 blocks = count / tape->tape_block_size;
2902                 while (count) {
2903                         atomic_set(&bh->b_count, min(count, (unsigned int)bh->b_size));
2904                         memset(bh->b_data, 0, atomic_read(&bh->b_count));
2905                         count -= atomic_read(&bh->b_count);
2906                         bh = bh->b_reqnext;
2907                 }
2908                 idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks, tape->merge_stage->bh);
2909         }
2910 }
2911
2912 static int idetape_pipeline_size (ide_drive_t *drive)
2913 {
2914         idetape_tape_t *tape = drive->driver_data;
2915         idetape_stage_t *stage;
2916         struct request *rq;
2917         int size = 0;
2918
2919         idetape_wait_for_pipeline(drive);
2920         stage = tape->first_stage;
2921         while (stage != NULL) {
2922                 rq = &stage->rq;
2923                 size += tape->tape_block_size * (rq->nr_sectors-rq->current_nr_sectors);
2924                 if (rq->errors == IDETAPE_ERROR_FILEMARK)
2925                         size += tape->tape_block_size;
2926                 stage = stage->next;
2927         }
2928         size += tape->merge_stage_size;
2929         return size;
2930 }
2931
2932 /*
2933  *      Rewinds the tape to the Beginning Of the current Partition (BOP).
2934  *
2935  *      We currently support only one partition.
2936  */ 
2937 static int idetape_rewind_tape (ide_drive_t *drive)
2938 {
2939         int retval;
2940         idetape_pc_t pc;
2941 #if IDETAPE_DEBUG_LOG
2942         idetape_tape_t *tape = drive->driver_data;
2943         if (tape->debug_level >= 2)
2944                 printk(KERN_INFO "ide-tape: Reached idetape_rewind_tape\n");
2945 #endif /* IDETAPE_DEBUG_LOG */  
2946         
2947         idetape_create_rewind_cmd(drive, &pc);
2948         retval = idetape_queue_pc_tail(drive, &pc);
2949         if (retval)
2950                 return retval;
2951
2952         idetape_create_read_position_cmd(&pc);
2953         retval = idetape_queue_pc_tail(drive, &pc);
2954         if (retval)
2955                 return retval;
2956         return 0;
2957 }
2958
2959 /*
2960  *      Our special ide-tape ioctl's.
2961  *
2962  *      Currently there aren't any ioctl's.
2963  *      mtio.h compatible commands should be issued to the character device
2964  *      interface.
2965  */
2966 static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd, unsigned long arg)
2967 {
2968         idetape_tape_t *tape = drive->driver_data;
2969         idetape_config_t config;
2970         void __user *argp = (void __user *)arg;
2971
2972 #if IDETAPE_DEBUG_LOG   
2973         if (tape->debug_level >= 4)
2974                 printk(KERN_INFO "ide-tape: Reached idetape_blkdev_ioctl\n");
2975 #endif /* IDETAPE_DEBUG_LOG */
2976         switch (cmd) {
2977                 case 0x0340:
2978                         if (copy_from_user(&config, argp, sizeof (idetape_config_t)))
2979                                 return -EFAULT;
2980                         tape->best_dsc_rw_frequency = config.dsc_rw_frequency;
2981                         tape->max_stages = config.nr_stages;
2982                         break;
2983                 case 0x0350:
2984                         config.dsc_rw_frequency = (int) tape->best_dsc_rw_frequency;
2985                         config.nr_stages = tape->max_stages; 
2986                         if (copy_to_user(argp, &config, sizeof (idetape_config_t)))
2987                                 return -EFAULT;
2988                         break;
2989                 default:
2990                         return -EIO;
2991         }
2992         return 0;
2993 }
2994
2995 /*
2996  *      idetape_space_over_filemarks is now a bit more complicated than just
2997  *      passing the command to the tape since we may have crossed some
2998  *      filemarks during our pipelined read-ahead mode.
2999  *
3000  *      As a minor side effect, the pipeline enables us to support MTFSFM when
3001  *      the filemark is in our internal pipeline even if the tape doesn't
3002  *      support spacing over filemarks in the reverse direction.
3003  */
3004 static int idetape_space_over_filemarks (ide_drive_t *drive,short mt_op,int mt_count)
3005 {
3006         idetape_tape_t *tape = drive->driver_data;
3007         idetape_pc_t pc;
3008         unsigned long flags;
3009         int retval,count=0;
3010         int sprev = !!(tape->caps[4] & 0x20);
3011
3012         if (mt_count == 0)
3013                 return 0;
3014         if (MTBSF == mt_op || MTBSFM == mt_op) {
3015                 if (!sprev)
3016                         return -EIO;
3017                 mt_count = - mt_count;
3018         }
3019
3020         if (tape->chrdev_direction == idetape_direction_read) {
3021                 /*
3022                  *      We have a read-ahead buffer. Scan it for crossed
3023                  *      filemarks.
3024                  */
3025                 tape->merge_stage_size = 0;
3026                 if (test_and_clear_bit(IDETAPE_FILEMARK, &tape->flags))
3027                         ++count;
3028                 while (tape->first_stage != NULL) {
3029                         if (count == mt_count) {
3030                                 if (mt_op == MTFSFM)
3031                                         set_bit(IDETAPE_FILEMARK, &tape->flags);
3032                                 return 0;
3033                         }
3034                         spin_lock_irqsave(&tape->spinlock, flags);
3035                         if (tape->first_stage == tape->active_stage) {
3036                                 /*
3037                                  *      We have reached the active stage in the read pipeline.
3038                                  *      There is no point in allowing the drive to continue
3039                                  *      reading any farther, so we stop the pipeline.
3040                                  *
3041                                  *      This section should be moved to a separate subroutine,
3042                                  *      because a similar function is performed in
3043                                  *      __idetape_discard_read_pipeline(), for example.
3044                                  */
3045                                 tape->next_stage = NULL;
3046                                 spin_unlock_irqrestore(&tape->spinlock, flags);
3047                                 idetape_wait_first_stage(drive);
3048                                 tape->next_stage = tape->first_stage->next;
3049                         } else
3050                                 spin_unlock_irqrestore(&tape->spinlock, flags);
3051                         if (tape->first_stage->rq.errors == IDETAPE_ERROR_FILEMARK)
3052                                 ++count;
3053                         idetape_remove_stage_head(drive);
3054                 }
3055                 idetape_discard_read_pipeline(drive, 0);
3056         }
3057
3058         /*
3059          *      The filemark was not found in our internal pipeline.
3060          *      Now we can issue the space command.
3061          */
3062         switch (mt_op) {
3063                 case MTFSF:
3064                 case MTBSF:
3065                         idetape_create_space_cmd(&pc,mt_count-count,IDETAPE_SPACE_OVER_FILEMARK);
3066                         return (idetape_queue_pc_tail(drive, &pc));
3067                 case MTFSFM:
3068                 case MTBSFM:
3069                         if (!sprev)
3070                                 return (-EIO);
3071                         retval = idetape_space_over_filemarks(drive, MTFSF, mt_count-count);
3072                         if (retval) return (retval);
3073                         count = (MTBSFM == mt_op ? 1 : -1);
3074                         return (idetape_space_over_filemarks(drive, MTFSF, count));
3075                 default:
3076                         printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",mt_op);
3077                         return (-EIO);
3078         }
3079 }
3080
3081
3082 /*
3083  *      Our character device read / write functions.
3084  *
3085  *      The tape is optimized to maximize throughput when it is transferring
3086  *      an integral number of the "continuous transfer limit", which is
3087  *      a parameter of the specific tape (26 KB on my particular tape).
3088  *      (32 kB for Onstream)
3089  *
3090  *      As of version 1.3 of the driver, the character device provides an
3091  *      abstract continuous view of the media - any mix of block sizes (even 1
3092  *      byte) on the same backup/restore procedure is supported. The driver
3093  *      will internally convert the requests to the recommended transfer unit,
3094  *      so that an unmatch between the user's block size to the recommended
3095  *      size will only result in a (slightly) increased driver overhead, but
3096  *      will no longer hit performance.
3097  *      This is not applicable to Onstream.
3098  */
3099 static ssize_t idetape_chrdev_read (struct file *file, char __user *buf,
3100                                     size_t count, loff_t *ppos)
3101 {
3102         struct ide_tape_obj *tape = ide_tape_f(file);
3103         ide_drive_t *drive = tape->drive;
3104         ssize_t bytes_read,temp, actually_read = 0, rc;
3105         ssize_t ret = 0;
3106         u16 ctl = *(u16 *)&tape->caps[12];
3107
3108 #if IDETAPE_DEBUG_LOG
3109         if (tape->debug_level >= 3)
3110                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_read, count %Zd\n", count);
3111 #endif /* IDETAPE_DEBUG_LOG */
3112
3113         if (tape->chrdev_direction != idetape_direction_read) {
3114                 if (test_bit(IDETAPE_DETECT_BS, &tape->flags))
3115                         if (count > tape->tape_block_size &&
3116                             (count % tape->tape_block_size) == 0)
3117                                 tape->user_bs_factor = count / tape->tape_block_size;
3118         }
3119         if ((rc = idetape_initiate_read(drive, tape->max_stages)) < 0)
3120                 return rc;
3121         if (count == 0)
3122                 return (0);
3123         if (tape->merge_stage_size) {
3124                 actually_read = min((unsigned int)(tape->merge_stage_size), (unsigned int)count);
3125                 if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage, actually_read))
3126                         ret = -EFAULT;
3127                 buf += actually_read;
3128                 tape->merge_stage_size -= actually_read;
3129                 count -= actually_read;
3130         }
3131         while (count >= tape->stage_size) {
3132                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
3133                 if (bytes_read <= 0)
3134                         goto finish;
3135                 if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage, bytes_read))
3136                         ret = -EFAULT;
3137                 buf += bytes_read;
3138                 count -= bytes_read;
3139                 actually_read += bytes_read;
3140         }
3141         if (count) {
3142                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
3143                 if (bytes_read <= 0)
3144                         goto finish;
3145                 temp = min((unsigned long)count, (unsigned long)bytes_read);
3146                 if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage, temp))
3147                         ret = -EFAULT;
3148                 actually_read += temp;
3149                 tape->merge_stage_size = bytes_read-temp;
3150         }
3151 finish:
3152         if (!actually_read && test_bit(IDETAPE_FILEMARK, &tape->flags)) {
3153 #if IDETAPE_DEBUG_LOG
3154                 if (tape->debug_level >= 2)
3155                         printk(KERN_INFO "ide-tape: %s: spacing over filemark\n", tape->name);
3156 #endif
3157                 idetape_space_over_filemarks(drive, MTFSF, 1);
3158                 return 0;
3159         }
3160
3161         return (ret) ? ret : actually_read;
3162 }
3163
3164 static ssize_t idetape_chrdev_write (struct file *file, const char __user *buf,
3165                                      size_t count, loff_t *ppos)
3166 {
3167         struct ide_tape_obj *tape = ide_tape_f(file);
3168         ide_drive_t *drive = tape->drive;
3169         ssize_t actually_written = 0;
3170         ssize_t ret = 0;
3171         u16 ctl = *(u16 *)&tape->caps[12];
3172
3173         /* The drive is write protected. */
3174         if (tape->write_prot)
3175                 return -EACCES;
3176
3177 #if IDETAPE_DEBUG_LOG
3178         if (tape->debug_level >= 3)
3179                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_write, "
3180                         "count %Zd\n", count);
3181 #endif /* IDETAPE_DEBUG_LOG */
3182
3183         /* Initialize write operation */
3184         if (tape->chrdev_direction != idetape_direction_write) {
3185                 if (tape->chrdev_direction == idetape_direction_read)
3186                         idetape_discard_read_pipeline(drive, 1);
3187                 if (tape->merge_stage || tape->merge_stage_size) {
3188                         printk(KERN_ERR "ide-tape: merge_stage_size "
3189                                 "should be 0 now\n");
3190                         tape->merge_stage_size = 0;
3191                 }
3192                 if ((tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0)) == NULL)
3193                         return -ENOMEM;
3194                 tape->chrdev_direction = idetape_direction_write;
3195                 idetape_init_merge_stage(tape);
3196
3197                 /*
3198                  *      Issue a write 0 command to ensure that DSC handshake
3199                  *      is switched from completion mode to buffer available
3200                  *      mode.
3201                  *      No point in issuing this if DSC overlap isn't supported,
3202                  *      some drives (Seagate STT3401A) will return an error.
3203                  */
3204                 if (drive->dsc_overlap) {
3205                         ssize_t retval = idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, 0, tape->merge_stage->bh);
3206                         if (retval < 0) {
3207                                 __idetape_kfree_stage(tape->merge_stage);
3208                                 tape->merge_stage = NULL;
3209                                 tape->chrdev_direction = idetape_direction_none;
3210                                 return retval;
3211                         }
3212                 }
3213         }
3214         if (count == 0)
3215                 return (0);
3216         if (tape->restart_speed_control_req)
3217                 idetape_restart_speed_control(drive);
3218         if (tape->merge_stage_size) {
3219                 if (tape->merge_stage_size >= tape->stage_size) {
3220                         printk(KERN_ERR "ide-tape: bug: merge buffer too big\n");
3221                         tape->merge_stage_size = 0;
3222                 }
3223                 actually_written = min((unsigned int)(tape->stage_size - tape->merge_stage_size), (unsigned int)count);
3224                 if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf, actually_written))
3225                                 ret = -EFAULT;
3226                 buf += actually_written;
3227                 tape->merge_stage_size += actually_written;
3228                 count -= actually_written;
3229
3230                 if (tape->merge_stage_size == tape->stage_size) {
3231                         ssize_t retval;
3232                         tape->merge_stage_size = 0;
3233                         retval = idetape_add_chrdev_write_request(drive, ctl);
3234                         if (retval <= 0)
3235                                 return (retval);
3236                 }
3237         }
3238         while (count >= tape->stage_size) {
3239                 ssize_t retval;
3240                 if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf, tape->stage_size))
3241                         ret = -EFAULT;
3242                 buf += tape->stage_size;
3243                 count -= tape->stage_size;
3244                 retval = idetape_add_chrdev_write_request(drive, ctl);
3245                 actually_written += tape->stage_size;
3246                 if (retval <= 0)
3247                         return (retval);
3248         }
3249         if (count) {
3250                 actually_written += count;
3251                 if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf, count))
3252                         ret = -EFAULT;
3253                 tape->merge_stage_size += count;
3254         }
3255         return (ret) ? ret : actually_written;
3256 }
3257
3258 static int idetape_write_filemark (ide_drive_t *drive)
3259 {
3260         idetape_pc_t pc;
3261
3262         /* Write a filemark */
3263         idetape_create_write_filemark_cmd(drive, &pc, 1);
3264         if (idetape_queue_pc_tail(drive, &pc)) {
3265                 printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
3266                 return -EIO;
3267         }
3268         return 0;
3269 }
3270
3271 /*
3272  *      idetape_mtioctop is called from idetape_chrdev_ioctl when
3273  *      the general mtio MTIOCTOP ioctl is requested.
3274  *
3275  *      We currently support the following mtio.h operations:
3276  *
3277  *      MTFSF   -       Space over mt_count filemarks in the positive direction.
3278  *                      The tape is positioned after the last spaced filemark.
3279  *
3280  *      MTFSFM  -       Same as MTFSF, but the tape is positioned before the
3281  *                      last filemark.
3282  *
3283  *      MTBSF   -       Steps background over mt_count filemarks, tape is
3284  *                      positioned before the last filemark.
3285  *
3286  *      MTBSFM  -       Like MTBSF, only tape is positioned after the last filemark.
3287  *
3288  *      Note:
3289  *
3290  *              MTBSF and MTBSFM are not supported when the tape doesn't
3291  *              support spacing over filemarks in the reverse direction.
3292  *              In this case, MTFSFM is also usually not supported (it is
3293  *              supported in the rare case in which we crossed the filemark
3294  *              during our read-ahead pipelined operation mode).
3295  *              
3296  *      MTWEOF  -       Writes mt_count filemarks. Tape is positioned after
3297  *                      the last written filemark.
3298  *
3299  *      MTREW   -       Rewinds tape.
3300  *
3301  *      MTLOAD  -       Loads the tape.
3302  *
3303  *      MTOFFL  -       Puts the tape drive "Offline": Rewinds the tape and
3304  *      MTUNLOAD        prevents further access until the media is replaced.
3305  *
3306  *      MTNOP   -       Flushes tape buffers.
3307  *
3308  *      MTRETEN -       Retension media. This typically consists of one end
3309  *                      to end pass on the media.
3310  *
3311  *      MTEOM   -       Moves to the end of recorded data.
3312  *
3313  *      MTERASE -       Erases tape.
3314  *
3315  *      MTSETBLK -      Sets the user block size to mt_count bytes. If
3316  *                      mt_count is 0, we will attempt to autodetect
3317  *                      the block size.
3318  *
3319  *      MTSEEK  -       Positions the tape in a specific block number, where
3320  *                      each block is assumed to contain which user_block_size
3321  *                      bytes.
3322  *
3323  *      MTSETPART -     Switches to another tape partition.
3324  *
3325  *      MTLOCK -        Locks the tape door.
3326  *
3327  *      MTUNLOCK -      Unlocks the tape door.
3328  *
3329  *      The following commands are currently not supported:
3330  *
3331  *      MTFSS, MTBSS, MTWSM, MTSETDENSITY,
3332  *      MTSETDRVBUFFER, MT_ST_BOOLEANS, MT_ST_WRITE_THRESHOLD.
3333  */
3334 static int idetape_mtioctop (ide_drive_t *drive,short mt_op,int mt_count)
3335 {
3336         idetape_tape_t *tape = drive->driver_data;
3337         idetape_pc_t pc;
3338         int i,retval;
3339
3340 #if IDETAPE_DEBUG_LOG
3341         if (tape->debug_level >= 1)
3342                 printk(KERN_INFO "ide-tape: Handling MTIOCTOP ioctl: "
3343                         "mt_op=%d, mt_count=%d\n", mt_op, mt_count);
3344 #endif /* IDETAPE_DEBUG_LOG */
3345         /*
3346          *      Commands which need our pipelined read-ahead stages.
3347          */
3348         switch (mt_op) {
3349                 case MTFSF:
3350                 case MTFSFM:
3351                 case MTBSF:
3352                 case MTBSFM:
3353                         if (!mt_count)
3354                                 return (0);
3355                         return (idetape_space_over_filemarks(drive,mt_op,mt_count));
3356                 default:
3357                         break;
3358         }
3359         switch (mt_op) {
3360                 case MTWEOF:
3361                         if (tape->write_prot)
3362                                 return -EACCES;
3363                         idetape_discard_read_pipeline(drive, 1);
3364                         for (i = 0; i < mt_count; i++) {
3365                                 retval = idetape_write_filemark(drive);
3366                                 if (retval)
3367                                         return retval;
3368                         }
3369                         return (0);
3370                 case MTREW:
3371                         idetape_discard_read_pipeline(drive, 0);
3372                         if (idetape_rewind_tape(drive))
3373                                 return -EIO;
3374                         return 0;
3375                 case MTLOAD:
3376                         idetape_discard_read_pipeline(drive, 0);
3377                         idetape_create_load_unload_cmd(drive, &pc, IDETAPE_LU_LOAD_MASK);
3378                         return (idetape_queue_pc_tail(drive, &pc));
3379                 case MTUNLOAD:
3380                 case MTOFFL:
3381                         /*
3382                          * If door is locked, attempt to unlock before
3383                          * attempting to eject.
3384                          */
3385                         if (tape->door_locked) {
3386                                 if (idetape_create_prevent_cmd(drive, &pc, 0))
3387                                         if (!idetape_queue_pc_tail(drive, &pc))
3388                                                 tape->door_locked = DOOR_UNLOCKED;
3389                         }
3390                         idetape_discard_read_pipeline(drive, 0);
3391                         idetape_create_load_unload_cmd(drive, &pc,!IDETAPE_LU_LOAD_MASK);
3392                         retval = idetape_queue_pc_tail(drive, &pc);
3393                         if (!retval)
3394                                 clear_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags);
3395                         return retval;
3396                 case MTNOP:
3397                         idetape_discard_read_pipeline(drive, 0);
3398                         return (idetape_flush_tape_buffers(drive));
3399                 case MTRETEN:
3400                         idetape_discard_read_pipeline(drive, 0);
3401                         idetape_create_load_unload_cmd(drive, &pc,IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
3402                         return (idetape_queue_pc_tail(drive, &pc));
3403                 case MTEOM:
3404                         idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
3405                         return (idetape_queue_pc_tail(drive, &pc));
3406                 case MTERASE:
3407                         (void) idetape_rewind_tape(drive);
3408                         idetape_create_erase_cmd(&pc);
3409                         return (idetape_queue_pc_tail(drive, &pc));
3410                 case MTSETBLK:
3411                         if (mt_count) {
3412                                 if (mt_count < tape->tape_block_size || mt_count % tape->tape_block_size)
3413                                         return -EIO;
3414                                 tape->user_bs_factor = mt_count / tape->tape_block_size;
3415                                 clear_bit(IDETAPE_DETECT_BS, &tape->flags);
3416                         } else
3417                                 set_bit(IDETAPE_DETECT_BS, &tape->flags);
3418                         return 0;
3419                 case MTSEEK:
3420                         idetape_discard_read_pipeline(drive, 0);
3421                         return idetape_position_tape(drive, mt_count * tape->user_bs_factor, tape->partition, 0);
3422                 case MTSETPART:
3423                         idetape_discard_read_pipeline(drive, 0);
3424                         return (idetape_position_tape(drive, 0, mt_count, 0));
3425                 case MTFSR:
3426                 case MTBSR:
3427                 case MTLOCK:
3428                         if (!idetape_create_prevent_cmd(drive, &pc, 1))
3429                                 return 0;
3430                         retval = idetape_queue_pc_tail(drive, &pc);
3431                         if (retval) return retval;
3432                         tape->door_locked = DOOR_EXPLICITLY_LOCKED;
3433                         return 0;
3434                 case MTUNLOCK:
3435                         if (!idetape_create_prevent_cmd(drive, &pc, 0))
3436                                 return 0;
3437                         retval = idetape_queue_pc_tail(drive, &pc);
3438                         if (retval) return retval;
3439                         tape->door_locked = DOOR_UNLOCKED;
3440                         return 0;
3441                 default:
3442                         printk(KERN_ERR "ide-tape: MTIO operation %d not "
3443                                 "supported\n", mt_op);
3444                         return (-EIO);
3445         }
3446 }
3447
3448 /*
3449  *      Our character device ioctls.
3450  *
3451  *      General mtio.h magnetic io commands are supported here, and not in
3452  *      the corresponding block interface.
3453  *
3454  *      The following ioctls are supported:
3455  *
3456  *      MTIOCTOP -      Refer to idetape_mtioctop for detailed description.
3457  *
3458  *      MTIOCGET -      The mt_dsreg field in the returned mtget structure
3459  *                      will be set to (user block size in bytes <<
3460  *                      MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK.
3461  *
3462  *                      The mt_blkno is set to the current user block number.
3463  *                      The other mtget fields are not supported.
3464  *
3465  *      MTIOCPOS -      The current tape "block position" is returned. We
3466  *                      assume that each block contains user_block_size
3467  *                      bytes.
3468  *
3469  *      Our own ide-tape ioctls are supported on both interfaces.
3470  */
3471 static int idetape_chrdev_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
3472 {
3473         struct ide_tape_obj *tape = ide_tape_f(file);
3474         ide_drive_t *drive = tape->drive;
3475         struct mtop mtop;
3476         struct mtget mtget;
3477         struct mtpos mtpos;
3478         int block_offset = 0, position = tape->first_frame_position;
3479         void __user *argp = (void __user *)arg;
3480
3481 #if IDETAPE_DEBUG_LOG
3482         if (tape->debug_level >= 3)
3483                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_ioctl, "
3484                         "cmd=%u\n", cmd);
3485 #endif /* IDETAPE_DEBUG_LOG */
3486
3487         tape->restart_speed_control_req = 1;
3488         if (tape->chrdev_direction == idetape_direction_write) {
3489                 idetape_empty_write_pipeline(drive);
3490                 idetape_flush_tape_buffers(drive);
3491         }
3492         if (cmd == MTIOCGET || cmd == MTIOCPOS) {
3493                 block_offset = idetape_pipeline_size(drive) / (tape->tape_block_size * tape->user_bs_factor);
3494                 if ((position = idetape_read_position(drive)) < 0)
3495                         return -EIO;
3496         }
3497         switch (cmd) {
3498                 case MTIOCTOP:
3499                         if (copy_from_user(&mtop, argp, sizeof (struct mtop)))
3500                                 return -EFAULT;
3501                         return (idetape_mtioctop(drive,mtop.mt_op,mtop.mt_count));
3502                 case MTIOCGET:
3503                         memset(&mtget, 0, sizeof (struct mtget));
3504                         mtget.mt_type = MT_ISSCSI2;
3505                         mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
3506                         mtget.mt_dsreg = ((tape->tape_block_size * tape->user_bs_factor) << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
3507                         if (tape->drv_write_prot) {
3508                                 mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
3509                         }
3510                         if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
3511                                 return -EFAULT;
3512                         return 0;
3513                 case MTIOCPOS:
3514                         mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
3515                         if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
3516                                 return -EFAULT;
3517                         return 0;
3518                 default:
3519                         if (tape->chrdev_direction == idetape_direction_read)
3520                                 idetape_discard_read_pipeline(drive, 1);
3521                         return idetape_blkdev_ioctl(drive, cmd, arg);
3522         }
3523 }
3524
3525 static void idetape_get_blocksize_from_block_descriptor(ide_drive_t *drive);
3526
3527 /*
3528  *      Our character device open function.
3529  */
3530 static int idetape_chrdev_open (struct inode *inode, struct file *filp)
3531 {
3532         unsigned int minor = iminor(inode), i = minor & ~0xc0;
3533         ide_drive_t *drive;
3534         idetape_tape_t *tape;
3535         idetape_pc_t pc;
3536         int retval;
3537
3538         /*
3539          * We really want to do nonseekable_open(inode, filp); here, but some
3540          * versions of tar incorrectly call lseek on tapes and bail out if that
3541          * fails.  So we disallow pread() and pwrite(), but permit lseeks.
3542          */
3543         filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
3544
3545 #if IDETAPE_DEBUG_LOG
3546         printk(KERN_INFO "ide-tape: Reached idetape_chrdev_open\n");
3547 #endif /* IDETAPE_DEBUG_LOG */
3548         
3549         if (i >= MAX_HWIFS * MAX_DRIVES)
3550                 return -ENXIO;
3551
3552         if (!(tape = ide_tape_chrdev_get(i)))
3553                 return -ENXIO;
3554
3555         drive = tape->drive;
3556
3557         filp->private_data = tape;
3558
3559         if (test_and_set_bit(IDETAPE_BUSY, &tape->flags)) {
3560                 retval = -EBUSY;
3561                 goto out_put_tape;
3562         }
3563
3564         retval = idetape_wait_ready(drive, 60 * HZ);
3565         if (retval) {
3566                 clear_bit(IDETAPE_BUSY, &tape->flags);
3567                 printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
3568                 goto out_put_tape;
3569         }
3570
3571         idetape_read_position(drive);
3572         if (!test_bit(IDETAPE_ADDRESS_VALID, &tape->flags))
3573                 (void)idetape_rewind_tape(drive);
3574
3575         if (tape->chrdev_direction != idetape_direction_read)
3576                 clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
3577
3578         /* Read block size and write protect status from drive. */
3579         idetape_get_blocksize_from_block_descriptor(drive);
3580
3581         /* Set write protect flag if device is opened as read-only. */
3582         if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
3583                 tape->write_prot = 1;
3584         else
3585                 tape->write_prot = tape->drv_write_prot;
3586
3587         /* Make sure drive isn't write protected if user wants to write. */
3588         if (tape->write_prot) {
3589                 if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
3590                     (filp->f_flags & O_ACCMODE) == O_RDWR) {
3591                         clear_bit(IDETAPE_BUSY, &tape->flags);
3592                         retval = -EROFS;
3593                         goto out_put_tape;
3594                 }
3595         }
3596
3597         /*
3598          * Lock the tape drive door so user can't eject.
3599          */
3600         if (tape->chrdev_direction == idetape_direction_none) {
3601                 if (idetape_create_prevent_cmd(drive, &pc, 1)) {
3602                         if (!idetape_queue_pc_tail(drive, &pc)) {
3603                                 if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
3604                                         tape->door_locked = DOOR_LOCKED;
3605                         }
3606                 }
3607         }
3608         idetape_restart_speed_control(drive);
3609         tape->restart_speed_control_req = 0;
3610         return 0;
3611
3612 out_put_tape:
3613         ide_tape_put(tape);
3614         return retval;
3615 }
3616
3617 static void idetape_write_release (ide_drive_t *drive, unsigned int minor)
3618 {
3619         idetape_tape_t *tape = drive->driver_data;
3620
3621         idetape_empty_write_pipeline(drive);
3622         tape->merge_stage = __idetape_kmalloc_stage(tape, 1, 0);
3623         if (tape->merge_stage != NULL) {
3624                 idetape_pad_zeros(drive, tape->tape_block_size * (tape->user_bs_factor - 1));
3625                 __idetape_kfree_stage(tape->merge_stage);
3626                 tape->merge_stage = NULL;
3627         }
3628         idetape_write_filemark(drive);
3629         idetape_flush_tape_buffers(drive);
3630         idetape_flush_tape_buffers(drive);
3631 }
3632
3633 /*
3634  *      Our character device release function.
3635  */
3636 static int idetape_chrdev_release (struct inode *inode, struct file *filp)
3637 {
3638         struct ide_tape_obj *tape = ide_tape_f(filp);
3639         ide_drive_t *drive = tape->drive;
3640         idetape_pc_t pc;
3641         unsigned int minor = iminor(inode);
3642
3643         lock_kernel();
3644         tape = drive->driver_data;
3645 #if IDETAPE_DEBUG_LOG
3646         if (tape->debug_level >= 3)
3647                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_release\n");
3648 #endif /* IDETAPE_DEBUG_LOG */
3649
3650         if (tape->chrdev_direction == idetape_direction_write)
3651                 idetape_write_release(drive, minor);
3652         if (tape->chrdev_direction == idetape_direction_read) {
3653                 if (minor < 128)
3654                         idetape_discard_read_pipeline(drive, 1);
3655                 else
3656                         idetape_wait_for_pipeline(drive);
3657         }
3658         if (tape->cache_stage != NULL) {
3659                 __idetape_kfree_stage(tape->cache_stage);
3660                 tape->cache_stage = NULL;
3661         }
3662         if (minor < 128 && test_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags))
3663                 (void) idetape_rewind_tape(drive);
3664         if (tape->chrdev_direction == idetape_direction_none) {
3665                 if (tape->door_locked == DOOR_LOCKED) {
3666                         if (idetape_create_prevent_cmd(drive, &pc, 0)) {
3667                                 if (!idetape_queue_pc_tail(drive, &pc))
3668                                         tape->door_locked = DOOR_UNLOCKED;
3669                         }
3670                 }
3671         }
3672         clear_bit(IDETAPE_BUSY, &tape->flags);
3673         ide_tape_put(tape);
3674         unlock_kernel();
3675         return 0;
3676 }
3677
3678 /*
3679  *      idetape_identify_device is called to check the contents of the
3680  *      ATAPI IDENTIFY command results. We return:
3681  *
3682  *      1       If the tape can be supported by us, based on the information
3683  *              we have so far.
3684  *
3685  *      0       If this tape driver is not currently supported by us.
3686  */
3687 static int idetape_identify_device (ide_drive_t *drive)
3688 {
3689         struct idetape_id_gcw gcw;
3690         struct hd_driveid *id = drive->id;
3691
3692         if (drive->id_read == 0)
3693                 return 1;
3694
3695         *((unsigned short *) &gcw) = id->config;
3696
3697         /* Check that we can support this device */
3698
3699         if (gcw.protocol != 2)
3700                 printk(KERN_ERR "ide-tape: Protocol (0x%02x) is not ATAPI\n",
3701                                 gcw.protocol);
3702         else if (gcw.device_type != 1)
3703                 printk(KERN_ERR "ide-tape: Device type (0x%02x) is not set "
3704                                 "to tape\n", gcw.device_type);
3705         else if (!gcw.removable)
3706                 printk(KERN_ERR "ide-tape: The removable flag is not set\n");
3707         else if (gcw.packet_size != 0) {
3708                 printk(KERN_ERR "ide-tape: Packet size (0x%02x) is not 12 "
3709                                 "bytes long\n", gcw.packet_size);
3710         } else
3711                 return 1;
3712         return 0;
3713 }
3714
3715 static void idetape_get_inquiry_results(ide_drive_t *drive)
3716 {
3717         char *r;
3718         idetape_tape_t *tape = drive->driver_data;
3719         idetape_pc_t pc;
3720
3721         idetape_create_inquiry_cmd(&pc);
3722         if (idetape_queue_pc_tail(drive, &pc)) {
3723                 printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
3724                                 tape->name);
3725                 return;
3726         }
3727         memcpy(tape->vendor_id, &pc.buffer[8], 8);
3728         memcpy(tape->product_id, &pc.buffer[16], 16);
3729         memcpy(tape->firmware_revision, &pc.buffer[32], 4);
3730
3731         ide_fixstring(tape->vendor_id, 10, 0);
3732         ide_fixstring(tape->product_id, 18, 0);
3733         ide_fixstring(tape->firmware_revision, 6, 0);
3734         r = tape->firmware_revision;
3735         if (*(r + 1) == '.')
3736                 tape->firmware_revision_num = (*r - '0') * 100 +
3737                         (*(r + 2) - '0') * 10 + *(r + 3) - '0';
3738         printk(KERN_INFO "ide-tape: %s <-> %s: %s %s rev %s\n",
3739                         drive->name, tape->name, tape->vendor_id,
3740                         tape->product_id, tape->firmware_revision);
3741 }
3742
3743 /*
3744  * Ask the tape about its various parameters. In particular, we will adjust our
3745  * data transfer buffer size to the recommended value as returned by the tape.
3746  */
3747 static void idetape_get_mode_sense_results (ide_drive_t *drive)
3748 {
3749         idetape_tape_t *tape = drive->driver_data;
3750         idetape_pc_t pc;
3751         u8 *caps;
3752         u8 speed, max_speed;
3753
3754         idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
3755         if (idetape_queue_pc_tail(drive, &pc)) {
3756                 printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
3757                                 " some default values\n");
3758                 tape->tape_block_size = 512;
3759                 put_unaligned(52,   (u16 *)&tape->caps[12]);
3760                 put_unaligned(540,  (u16 *)&tape->caps[14]);
3761                 put_unaligned(6*52, (u16 *)&tape->caps[16]);
3762                 return;
3763         }
3764         caps = pc.buffer + 4 + pc.buffer[3];
3765
3766         /* convert to host order and save for later use */
3767         speed = be16_to_cpu(*(u16 *)&caps[14]);
3768         max_speed = be16_to_cpu(*(u16 *)&caps[8]);
3769
3770         put_unaligned(max_speed, (u16 *)&caps[8]);
3771         put_unaligned(be16_to_cpu(*(u16 *)&caps[12]), (u16 *)&caps[12]);
3772         put_unaligned(speed, (u16 *)&caps[14]);
3773         put_unaligned(be16_to_cpu(*(u16 *)&caps[16]), (u16 *)&caps[16]);
3774
3775         if (!speed) {
3776                 printk(KERN_INFO "ide-tape: %s: invalid tape speed "
3777                                 "(assuming 650KB/sec)\n", drive->name);
3778                 put_unaligned(650, (u16 *)&caps[14]);
3779         }
3780         if (!max_speed) {
3781                 printk(KERN_INFO "ide-tape: %s: invalid max_speed "
3782                                 "(assuming 650KB/sec)\n", drive->name);
3783                 put_unaligned(650, (u16 *)&caps[8]);
3784         }
3785
3786         memcpy(&tape->caps, caps, 20);
3787         if (caps[7] & 0x02)
3788                 tape->tape_block_size = 512;
3789         else if (caps[7] & 0x04)
3790                 tape->tape_block_size = 1024;
3791 }
3792
3793 /*
3794  *      ide_get_blocksize_from_block_descriptor does a mode sense page 0 with block descriptor
3795  *      and if it succeeds sets the tape block size with the reported value
3796  */
3797 static void idetape_get_blocksize_from_block_descriptor(ide_drive_t *drive)
3798 {
3799
3800         idetape_tape_t *tape = drive->driver_data;
3801         idetape_pc_t pc;
3802         idetape_parameter_block_descriptor_t *block_descrp;
3803
3804         idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
3805         if (idetape_queue_pc_tail(drive, &pc)) {
3806                 printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
3807                 if (tape->tape_block_size == 0) {
3808                         printk(KERN_WARNING "ide-tape: Cannot deal with zero block size, assume 32k\n");
3809                         tape->tape_block_size =  32768;
3810                 }
3811                 return;
3812         }
3813         block_descrp = (idetape_parameter_block_descriptor_t *)(pc.buffer + 4);
3814         tape->tape_block_size =( block_descrp->length[0]<<16) + (block_descrp->length[1]<<8) + block_descrp->length[2];
3815         tape->drv_write_prot = (pc.buffer[2] & 0x80) >> 7;
3816 }
3817
3818 #ifdef CONFIG_IDE_PROC_FS
3819 static void idetape_add_settings (ide_drive_t *drive)
3820 {
3821         idetape_tape_t *tape = drive->driver_data;
3822
3823 /*
3824  *                      drive   setting name            read/write      data type       min                     max                     mul_factor                      div_factor      data pointer                            set function
3825  */
3826         ide_add_setting(drive, "buffer", SETTING_READ, TYPE_SHORT, 0, 0xffff,
3827                         1, 2, (u16 *)&tape->caps[16], NULL);
3828         ide_add_setting(drive,  "pipeline_min",         SETTING_RW,     TYPE_INT,       1,                      0xffff,                 tape->stage_size / 1024,        1,              &tape->min_pipeline,                    NULL);
3829         ide_add_setting(drive,  "pipeline",             SETTING_RW,     TYPE_INT,       1,                      0xffff,                 tape->stage_size / 1024,        1,              &tape->max_stages,                      NULL);
3830         ide_add_setting(drive,  "pipeline_max",         SETTING_RW,     TYPE_INT,       1,                      0xffff,                 tape->stage_size / 1024,        1,              &tape->max_pipeline,                    NULL);
3831         ide_add_setting(drive,  "pipeline_used",        SETTING_READ,   TYPE_INT,       0,                      0xffff,                 tape->stage_size / 1024,        1,              &tape->nr_stages,                       NULL);
3832         ide_add_setting(drive,  "pipeline_pending",     SETTING_READ,   TYPE_INT,       0,                      0xffff,                 tape->stage_size / 1024,        1,              &tape->nr_pending_stages,               NULL);
3833         ide_add_setting(drive, "speed", SETTING_READ, TYPE_SHORT, 0, 0xffff,
3834                         1, 1, (u16 *)&tape->caps[14], NULL);
3835         ide_add_setting(drive,  "stage",                SETTING_READ,   TYPE_INT,       0,                      0xffff,                 1,                              1024,           &tape->stage_size,                      NULL);
3836         ide_add_setting(drive,  "tdsc",                 SETTING_RW,     TYPE_INT,       IDETAPE_DSC_RW_MIN,     IDETAPE_DSC_RW_MAX,     1000,                           HZ,             &tape->best_dsc_rw_frequency,           NULL);
3837         ide_add_setting(drive,  "dsc_overlap",          SETTING_RW,     TYPE_BYTE,      0,                      1,                      1,                              1,              &drive->dsc_overlap,                    NULL);
3838         ide_add_setting(drive,  "pipeline_head_speed_c",SETTING_READ,   TYPE_INT,       0,                      0xffff,                 1,                              1,              &tape->controlled_pipeline_head_speed,  NULL);
3839         ide_add_setting(drive,  "pipeline_head_speed_u",SETTING_READ,   TYPE_INT,       0,                      0xffff,                 1,                              1,              &tape->uncontrolled_pipeline_head_speed,NULL);
3840         ide_add_setting(drive,  "avg_speed",            SETTING_READ,   TYPE_INT,       0,                      0xffff,                 1,                              1,              &tape->avg_speed,                       NULL);
3841         ide_add_setting(drive,  "debug_level",          SETTING_RW,     TYPE_INT,       0,                      0xffff,                 1,                              1,              &tape->debug_level,                     NULL);
3842 }
3843 #else
3844 static inline void idetape_add_settings(ide_drive_t *drive) { ; }
3845 #endif
3846
3847 /*
3848  *      ide_setup is called to:
3849  *
3850  *              1.      Initialize our various state variables.
3851  *              2.      Ask the tape for its capabilities.
3852  *              3.      Allocate a buffer which will be used for data
3853  *                      transfer. The buffer size is chosen based on
3854  *                      the recommendation which we received in step (2).
3855  *
3856  *      Note that at this point ide.c already assigned us an irq, so that
3857  *      we can queue requests here and wait for their completion.
3858  */
3859 static void idetape_setup (ide_drive_t *drive, idetape_tape_t *tape, int minor)
3860 {
3861         unsigned long t1, tmid, tn, t;
3862         int speed;
3863         struct idetape_id_gcw gcw;
3864         int stage_size;
3865         struct sysinfo si;
3866         u16 *ctl = (u16 *)&tape->caps[12];
3867
3868         spin_lock_init(&tape->spinlock);
3869         drive->dsc_overlap = 1;
3870         if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
3871                 printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
3872                                  tape->name);
3873                 drive->dsc_overlap = 0;
3874         }
3875         /* Seagate Travan drives do not support DSC overlap. */
3876         if (strstr(drive->id->model, "Seagate STT3401"))
3877                 drive->dsc_overlap = 0;
3878         tape->minor = minor;
3879         tape->name[0] = 'h';
3880         tape->name[1] = 't';
3881         tape->name[2] = '0' + minor;
3882         tape->chrdev_direction = idetape_direction_none;
3883         tape->pc = tape->pc_stack;
3884         tape->max_insert_speed = 10000;
3885         tape->speed_control = 1;
3886         *((unsigned short *) &gcw) = drive->id->config;
3887         if (gcw.drq_type == 1)
3888                 set_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags);
3889
3890         tape->min_pipeline = tape->max_pipeline = tape->max_stages = 10;
3891         
3892         idetape_get_inquiry_results(drive);
3893         idetape_get_mode_sense_results(drive);
3894         idetape_get_blocksize_from_block_descriptor(drive);
3895         tape->user_bs_factor = 1;
3896         tape->stage_size = *ctl * tape->tape_block_size;
3897         while (tape->stage_size > 0xffff) {
3898                 printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
3899                 *ctl /= 2;
3900                 tape->stage_size = *ctl * tape->tape_block_size;
3901         }
3902         stage_size = tape->stage_size;
3903         tape->pages_per_stage = stage_size / PAGE_SIZE;
3904         if (stage_size % PAGE_SIZE) {
3905                 tape->pages_per_stage++;
3906                 tape->excess_bh_size = PAGE_SIZE - stage_size % PAGE_SIZE;
3907         }
3908
3909         /* Select the "best" DSC read/write polling freq and pipeline size. */
3910         speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
3911
3912         tape->max_stages = speed * 1000 * 10 / tape->stage_size;
3913
3914         /*
3915          *      Limit memory use for pipeline to 10% of physical memory
3916          */
3917         si_meminfo(&si);
3918         if (tape->max_stages * tape->stage_size > si.totalram * si.mem_unit / 10)
3919                 tape->max_stages = si.totalram * si.mem_unit / (10 * tape->stage_size);
3920         tape->max_stages   = min(tape->max_stages, IDETAPE_MAX_PIPELINE_STAGES);
3921         tape->min_pipeline = min(tape->max_stages, IDETAPE_MIN_PIPELINE_STAGES);
3922         tape->max_pipeline = min(tape->max_stages * 2, IDETAPE_MAX_PIPELINE_STAGES);
3923         if (tape->max_stages == 0)
3924                 tape->max_stages = tape->min_pipeline = tape->max_pipeline = 1;
3925
3926         t1 = (tape->stage_size * HZ) / (speed * 1000);
3927         tmid = (*(u16 *)&tape->caps[16] * 32 * HZ) / (speed * 125);
3928         tn = (IDETAPE_FIFO_THRESHOLD * tape->stage_size * HZ) / (speed * 1000);
3929
3930         if (tape->max_stages)
3931                 t = tn;
3932         else
3933                 t = t1;
3934
3935         /*
3936          *      Ensure that the number we got makes sense; limit
3937          *      it within IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
3938          */
3939         tape->best_dsc_rw_frequency = max_t(unsigned long, min_t(unsigned long, t, IDETAPE_DSC_RW_MAX), IDETAPE_DSC_RW_MIN);
3940         printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
3941                 "%dkB pipeline, %lums tDSC%s\n",
3942                 drive->name, tape->name, *(u16 *)&tape->caps[14],
3943                 (*(u16 *)&tape->caps[16] * 512) / tape->stage_size,
3944                 tape->stage_size / 1024,
3945                 tape->max_stages * tape->stage_size / 1024,
3946                 tape->best_dsc_rw_frequency * 1000 / HZ,
3947                 drive->using_dma ? ", DMA":"");
3948
3949         idetape_add_settings(drive);
3950 }
3951
3952 static void ide_tape_remove(ide_drive_t *drive)
3953 {
3954         idetape_tape_t *tape = drive->driver_data;
3955
3956         ide_proc_unregister_driver(drive, tape->driver);
3957
3958         ide_unregister_region(tape->disk);
3959
3960         ide_tape_put(tape);
3961 }
3962
3963 static void ide_tape_release(struct kref *kref)
3964 {
3965         struct ide_tape_obj *tape = to_ide_tape(kref);
3966         ide_drive_t *drive = tape->drive;
3967         struct gendisk *g = tape->disk;
3968
3969         BUG_ON(tape->first_stage != NULL || tape->merge_stage_size);
3970
3971         drive->dsc_overlap = 0;
3972         drive->driver_data = NULL;
3973         device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
3974         device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor + 128));
3975         idetape_devs[tape->minor] = NULL;
3976         g->private_data = NULL;
3977         put_disk(g);
3978         kfree(tape);
3979 }
3980
3981 #ifdef CONFIG_IDE_PROC_FS
3982 static int proc_idetape_read_name
3983         (char *page, char **start, off_t off, int count, int *eof, void *data)
3984 {
3985         ide_drive_t     *drive = (ide_drive_t *) data;
3986         idetape_tape_t  *tape = drive->driver_data;
3987         char            *out = page;
3988         int             len;
3989
3990         len = sprintf(out, "%s\n", tape->name);
3991         PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
3992 }
3993
3994 static ide_proc_entry_t idetape_proc[] = {
3995         { "capacity",   S_IFREG|S_IRUGO,        proc_ide_read_capacity, NULL },
3996         { "name",       S_IFREG|S_IRUGO,        proc_idetape_read_name, NULL },
3997         { NULL, 0, NULL, NULL }
3998 };
3999 #endif
4000
4001 static int ide_tape_probe(ide_drive_t *);
4002
4003 static ide_driver_t idetape_driver = {
4004         .gen_driver = {
4005                 .owner          = THIS_MODULE,
4006                 .name           = "ide-tape",
4007                 .bus            = &ide_bus_type,
4008         },
4009         .probe                  = ide_tape_probe,
4010         .remove                 = ide_tape_remove,
4011         .version                = IDETAPE_VERSION,
4012         .media                  = ide_tape,
4013         .supports_dsc_overlap   = 1,
4014         .do_request             = idetape_do_request,
4015         .end_request            = idetape_end_request,
4016         .error                  = __ide_error,
4017         .abort                  = __ide_abort,
4018 #ifdef CONFIG_IDE_PROC_FS
4019         .proc                   = idetape_proc,
4020 #endif
4021 };
4022
4023 /*
4024  *      Our character device supporting functions, passed to register_chrdev.
4025  */
4026 static const struct file_operations idetape_fops = {
4027         .owner          = THIS_MODULE,
4028         .read           = idetape_chrdev_read,
4029         .write          = idetape_chrdev_write,
4030         .ioctl          = idetape_chrdev_ioctl,
4031         .open           = idetape_chrdev_open,
4032         .release        = idetape_chrdev_release,
4033 };
4034
4035 static int idetape_open(struct inode *inode, struct file *filp)
4036 {
4037         struct gendisk *disk = inode->i_bdev->bd_disk;
4038         struct ide_tape_obj *tape;
4039
4040         if (!(tape = ide_tape_get(disk)))
4041                 return -ENXIO;
4042
4043         return 0;
4044 }
4045
4046 static int idetape_release(struct inode *inode, struct file *filp)
4047 {
4048         struct gendisk *disk = inode->i_bdev->bd_disk;
4049         struct ide_tape_obj *tape = ide_tape_g(disk);
4050
4051         ide_tape_put(tape);
4052
4053         return 0;
4054 }
4055
4056 static int idetape_ioctl(struct inode *inode, struct file *file,
4057                         unsigned int cmd, unsigned long arg)
4058 {
4059         struct block_device *bdev = inode->i_bdev;
4060         struct ide_tape_obj *tape = ide_tape_g(bdev->bd_disk);
4061         ide_drive_t *drive = tape->drive;
4062         int err = generic_ide_ioctl(drive, file, bdev, cmd, arg);
4063         if (err == -EINVAL)
4064                 err = idetape_blkdev_ioctl(drive, cmd, arg);
4065         return err;
4066 }
4067
4068 static struct block_device_operations idetape_block_ops = {
4069         .owner          = THIS_MODULE,
4070         .open           = idetape_open,
4071         .release        = idetape_release,
4072         .ioctl          = idetape_ioctl,
4073 };
4074
4075 static int ide_tape_probe(ide_drive_t *drive)
4076 {
4077         idetape_tape_t *tape;
4078         struct gendisk *g;
4079         int minor;
4080
4081         if (!strstr("ide-tape", drive->driver_req))
4082                 goto failed;
4083         if (!drive->present)
4084                 goto failed;
4085         if (drive->media != ide_tape)
4086                 goto failed;
4087         if (!idetape_identify_device (drive)) {
4088                 printk(KERN_ERR "ide-tape: %s: not supported by this version of ide-tape\n", drive->name);
4089                 goto failed;
4090         }
4091         if (drive->scsi) {
4092                 printk("ide-tape: passing drive %s to ide-scsi emulation.\n", drive->name);
4093                 goto failed;
4094         }
4095         if (strstr(drive->id->model, "OnStream DI-")) {
4096                 printk(KERN_WARNING "ide-tape: Use drive %s with ide-scsi emulation and osst.\n", drive->name);
4097                 printk(KERN_WARNING "ide-tape: OnStream support will be removed soon from ide-tape!\n");
4098         }
4099         tape = kzalloc(sizeof (idetape_tape_t), GFP_KERNEL);
4100         if (tape == NULL) {
4101                 printk(KERN_ERR "ide-tape: %s: Can't allocate a tape structure\n", drive->name);
4102                 goto failed;
4103         }
4104
4105         g = alloc_disk(1 << PARTN_BITS);
4106         if (!g)
4107                 goto out_free_tape;
4108
4109         ide_init_disk(g, drive);
4110
4111         ide_proc_register_driver(drive, &idetape_driver);
4112
4113         kref_init(&tape->kref);
4114
4115         tape->drive = drive;
4116         tape->driver = &idetape_driver;
4117         tape->disk = g;
4118
4119         g->private_data = &tape->driver;
4120
4121         drive->driver_data = tape;
4122
4123         mutex_lock(&idetape_ref_mutex);
4124         for (minor = 0; idetape_devs[minor]; minor++)
4125                 ;
4126         idetape_devs[minor] = tape;
4127         mutex_unlock(&idetape_ref_mutex);
4128
4129         idetape_setup(drive, tape, minor);
4130
4131         device_create(idetape_sysfs_class, &drive->gendev,
4132                       MKDEV(IDETAPE_MAJOR, minor), "%s", tape->name);
4133         device_create(idetape_sysfs_class, &drive->gendev,
4134                         MKDEV(IDETAPE_MAJOR, minor + 128), "n%s", tape->name);
4135
4136         g->fops = &idetape_block_ops;
4137         ide_register_region(g);
4138
4139         return 0;
4140
4141 out_free_tape:
4142         kfree(tape);
4143 failed:
4144         return -ENODEV;
4145 }
4146
4147 MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
4148 MODULE_LICENSE("GPL");
4149
4150 static void __exit idetape_exit (void)
4151 {
4152         driver_unregister(&idetape_driver.gen_driver);
4153         class_destroy(idetape_sysfs_class);
4154         unregister_chrdev(IDETAPE_MAJOR, "ht");
4155 }
4156
4157 static int __init idetape_init(void)
4158 {
4159         int error = 1;
4160         idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
4161         if (IS_ERR(idetape_sysfs_class)) {
4162                 idetape_sysfs_class = NULL;
4163                 printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
4164                 error = -EBUSY;
4165                 goto out;
4166         }
4167
4168         if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
4169                 printk(KERN_ERR "ide-tape: Failed to register character device interface\n");
4170                 error = -EBUSY;
4171                 goto out_free_class;
4172         }
4173
4174         error = driver_register(&idetape_driver.gen_driver);
4175         if (error)
4176                 goto out_free_driver;
4177
4178         return 0;
4179
4180 out_free_driver:
4181         driver_unregister(&idetape_driver.gen_driver);
4182 out_free_class:
4183         class_destroy(idetape_sysfs_class);
4184 out:
4185         return error;
4186 }
4187
4188 MODULE_ALIAS("ide:*m-tape*");
4189 module_init(idetape_init);
4190 module_exit(idetape_exit);
4191 MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);