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