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