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