]> err.no Git - linux-2.6/blob - drivers/ide/ide-tape.c
ide: fix for EATA SCSI HBA in ATA emulating mode
[linux-2.6] / drivers / ide / ide-tape.c
1 /*
2  * IDE ATAPI streaming tape driver.
3  *
4  * Copyright (C) 1995-1999  Gadi Oxman <gadio@netvision.net.il>
5  * Copyright (C) 2003-2005  Bartlomiej Zolnierkiewicz
6  *
7  * This driver was constructed as a student project in the software laboratory
8  * of the faculty of electrical engineering in the Technion - Israel's
9  * Institute Of Technology, with the guide of Avner Lottem and Dr. Ilana David.
10  *
11  * It is hereby placed under the terms of the GNU general public license.
12  * (See linux/COPYING).
13  *
14  * For a historical changelog see
15  * Documentation/ide/ChangeLog.ide-tape.1995-2002
16  */
17
18 #define IDETAPE_VERSION "1.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  * After each failed packet command we issue a request sense command and retry
77  * the packet command IDETAPE_MAX_PC_RETRIES times.
78  *
79  * Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
80  */
81 #define IDETAPE_MAX_PC_RETRIES          3
82
83 /*
84  * With each packet command, we allocate a buffer of IDETAPE_PC_BUFFER_SIZE
85  * bytes. This is used for several packet commands (Not for READ/WRITE commands)
86  */
87 #define IDETAPE_PC_BUFFER_SIZE          256
88
89 /*
90  *      In various places in the driver, we need to allocate storage
91  *      for packet commands and requests, which will remain valid while
92  *      we leave the driver to wait for an interrupt or a timeout event.
93  */
94 #define IDETAPE_PC_STACK                (10 + IDETAPE_MAX_PC_RETRIES)
95
96 /*
97  * Some drives (for example, Seagate STT3401A Travan) require a very long
98  * timeout, because they don't return an interrupt or clear their busy bit
99  * until after the command completes (even retension commands).
100  */
101 #define IDETAPE_WAIT_CMD                (900*HZ)
102
103 /*
104  * The following parameter is used to select the point in the internal tape fifo
105  * in which we will start to refill the buffer. Decreasing the following
106  * parameter will improve the system's latency and interactive response, while
107  * using a high value might improve system throughput.
108  */
109 #define IDETAPE_FIFO_THRESHOLD          2
110
111 /*
112  * DSC polling parameters.
113  *
114  * Polling for DSC (a single bit in the status register) is a very important
115  * function in ide-tape. There are two cases in which we poll for DSC:
116  *
117  * 1. Before a read/write packet command, to ensure that we can transfer data
118  * from/to the tape's data buffers, without causing an actual media access.
119  * In case the tape is not ready yet, we take out our request from the device
120  * request queue, so that ide.c could service requests from the other device
121  * on the same interface in the meantime.
122  *
123  * 2. After the successful initialization of a "media access packet command",
124  * which is a command that can take a long time to complete (the interval can
125  * range from several seconds to even an hour). Again, we postpone our request
126  * in the middle to free the bus for the other device. The polling frequency
127  * here should be lower than the read/write frequency since those media access
128  * commands are slow. We start from a "fast" frequency - IDETAPE_DSC_MA_FAST
129  * (1 second), and if we don't receive DSC after IDETAPE_DSC_MA_THRESHOLD
130  * (5 min), we switch it to a lower frequency - IDETAPE_DSC_MA_SLOW (1 min).
131  *
132  * We also set a timeout for the timer, in case something goes wrong. The
133  * timeout should be longer then the maximum execution time of a tape operation.
134  */
135
136 /* DSC timings. */
137 #define IDETAPE_DSC_RW_MIN              5*HZ/100        /* 50 msec */
138 #define IDETAPE_DSC_RW_MAX              40*HZ/100       /* 400 msec */
139 #define IDETAPE_DSC_RW_TIMEOUT          2*60*HZ         /* 2 minutes */
140 #define IDETAPE_DSC_MA_FAST             2*HZ            /* 2 seconds */
141 #define IDETAPE_DSC_MA_THRESHOLD        5*60*HZ         /* 5 minutes */
142 #define IDETAPE_DSC_MA_SLOW             30*HZ           /* 30 seconds */
143 #define IDETAPE_DSC_MA_TIMEOUT          2*60*60*HZ      /* 2 hours */
144
145 /*************************** End of tunable parameters ***********************/
146
147 /* tape directions */
148 enum {
149         IDETAPE_DIR_NONE  = (1 << 0),
150         IDETAPE_DIR_READ  = (1 << 1),
151         IDETAPE_DIR_WRITE = (1 << 2),
152 };
153
154 struct idetape_bh {
155         u32 b_size;
156         atomic_t b_count;
157         struct idetape_bh *b_reqnext;
158         char *b_data;
159 };
160
161 /* Tape door status */
162 #define DOOR_UNLOCKED                   0
163 #define DOOR_LOCKED                     1
164 #define DOOR_EXPLICITLY_LOCKED          2
165
166 /* Some defines for the SPACE command */
167 #define IDETAPE_SPACE_OVER_FILEMARK     1
168 #define IDETAPE_SPACE_TO_EOD            3
169
170 /* Some defines for the LOAD UNLOAD command */
171 #define IDETAPE_LU_LOAD_MASK            1
172 #define IDETAPE_LU_RETENSION_MASK       2
173 #define IDETAPE_LU_EOT_MASK             4
174
175 /*
176  * Special requests for our block device strategy routine.
177  *
178  * In order to service a character device command, we add special requests to
179  * the tail of our block device request queue and wait for their completion.
180  */
181
182 enum {
183         REQ_IDETAPE_PC1         = (1 << 0), /* packet command (first stage) */
184         REQ_IDETAPE_PC2         = (1 << 1), /* packet command (second stage) */
185         REQ_IDETAPE_READ        = (1 << 2),
186         REQ_IDETAPE_WRITE       = (1 << 3),
187 };
188
189 /* Error codes returned in rq->errors to the higher part of the driver. */
190 #define IDETAPE_ERROR_GENERAL           101
191 #define IDETAPE_ERROR_FILEMARK          102
192 #define IDETAPE_ERROR_EOD               103
193
194 /* Structures related to the SELECT SENSE / MODE SENSE packet commands. */
195 #define IDETAPE_BLOCK_DESCRIPTOR        0
196 #define IDETAPE_CAPABILITIES_PAGE       0x2a
197
198 /*
199  * Most of our global data which we need to save even as we leave the driver due
200  * to an interrupt or a timer event is stored in the struct defined below.
201  */
202 typedef struct ide_tape_obj {
203         ide_drive_t     *drive;
204         ide_driver_t    *driver;
205         struct gendisk  *disk;
206         struct kref     kref;
207
208         /*
209          *      Since a typical character device operation requires more
210          *      than one packet command, we provide here enough memory
211          *      for the maximum of interconnected packet commands.
212          *      The packet commands are stored in the circular array pc_stack.
213          *      pc_stack_index points to the last used entry, and warps around
214          *      to the start when we get to the last array entry.
215          *
216          *      pc points to the current processed packet command.
217          *
218          *      failed_pc points to the last failed packet command, or contains
219          *      NULL if we do not need to retry any packet command. This is
220          *      required since an additional packet command is needed before the
221          *      retry, to get detailed information on what went wrong.
222          */
223         /* Current packet command */
224         struct ide_atapi_pc *pc;
225         /* Last failed packet command */
226         struct ide_atapi_pc *failed_pc;
227         /* Packet command stack */
228         struct ide_atapi_pc pc_stack[IDETAPE_PC_STACK];
229         /* Next free packet command storage space */
230         int pc_stack_index;
231         struct request rq_stack[IDETAPE_PC_STACK];
232         /* We implement a circular array */
233         int rq_stack_index;
234
235         /*
236          * DSC polling variables.
237          *
238          * While polling for DSC we use postponed_rq to postpone the current
239          * request so that ide.c will be able to service pending requests on the
240          * other device. Note that at most we will have only one DSC (usually
241          * data transfer) request in the device request queue.
242          */
243         struct request *postponed_rq;
244         /* The time in which we started polling for DSC */
245         unsigned long dsc_polling_start;
246         /* Timer used to poll for dsc */
247         struct timer_list dsc_timer;
248         /* Read/Write dsc polling frequency */
249         unsigned long best_dsc_rw_freq;
250         unsigned long dsc_poll_freq;
251         unsigned long dsc_timeout;
252
253         /* Read position information */
254         u8 partition;
255         /* Current block */
256         unsigned int first_frame;
257
258         /* Last error information */
259         u8 sense_key, asc, ascq;
260
261         /* Character device operation */
262         unsigned int minor;
263         /* device name */
264         char name[4];
265         /* Current character device data transfer direction */
266         u8 chrdev_dir;
267
268         /* tape block size, usually 512 or 1024 bytes */
269         unsigned short blk_size;
270         int user_bs_factor;
271
272         /* Copy of the tape's Capabilities and Mechanical Page */
273         u8 caps[20];
274
275         /*
276          * Active data transfer request parameters.
277          *
278          * At most, there is only one ide-tape originated data transfer request
279          * in the device request queue. This allows ide.c to easily service
280          * requests from the other device when we postpone our active request.
281          */
282
283         /* Data buffer size chosen based on the tape's recommendation */
284         int buffer_size;
285         /* merge buffer */
286         struct idetape_bh *merge_bh;
287         /* size of the merge buffer */
288         int merge_bh_size;
289         /* pointer to current buffer head within the merge buffer */
290         struct idetape_bh *bh;
291         char *b_data;
292         int b_count;
293
294         int pages_per_buffer;
295         /* Wasted space in each stage */
296         int excess_bh_size;
297
298         /* protects the ide-tape queue */
299         spinlock_t lock;
300
301         /* Measures average tape speed */
302         unsigned long avg_time;
303         int avg_size;
304         int avg_speed;
305
306         /* the door is currently locked */
307         int door_locked;
308         /* the tape hardware is write protected */
309         char drv_write_prot;
310         /* the tape is write protected (hardware or opened as read-only) */
311         char write_prot;
312
313         u32 debug_mask;
314 } idetape_tape_t;
315
316 static DEFINE_MUTEX(idetape_ref_mutex);
317
318 static struct class *idetape_sysfs_class;
319
320 #define to_ide_tape(obj) container_of(obj, struct ide_tape_obj, kref)
321
322 #define ide_tape_g(disk) \
323         container_of((disk)->private_data, struct ide_tape_obj, driver)
324
325 static void ide_tape_release(struct kref *);
326
327 static struct ide_tape_obj *ide_tape_get(struct gendisk *disk)
328 {
329         struct ide_tape_obj *tape = NULL;
330
331         mutex_lock(&idetape_ref_mutex);
332         tape = ide_tape_g(disk);
333         if (tape) {
334                 kref_get(&tape->kref);
335                 if (ide_device_get(tape->drive)) {
336                         kref_put(&tape->kref, ide_tape_release);
337                         tape = NULL;
338                 }
339         }
340         mutex_unlock(&idetape_ref_mutex);
341         return tape;
342 }
343
344 static void ide_tape_put(struct ide_tape_obj *tape)
345 {
346         mutex_lock(&idetape_ref_mutex);
347         ide_device_put(tape->drive);
348         kref_put(&tape->kref, ide_tape_release);
349         mutex_unlock(&idetape_ref_mutex);
350 }
351
352 /*
353  * The variables below are used for the character device interface. Additional
354  * state variables are defined in our ide_drive_t structure.
355  */
356 static struct ide_tape_obj *idetape_devs[MAX_HWIFS * MAX_DRIVES];
357
358 #define ide_tape_f(file) ((file)->private_data)
359
360 static struct ide_tape_obj *ide_tape_chrdev_get(unsigned int i)
361 {
362         struct ide_tape_obj *tape = NULL;
363
364         mutex_lock(&idetape_ref_mutex);
365         tape = idetape_devs[i];
366         if (tape)
367                 kref_get(&tape->kref);
368         mutex_unlock(&idetape_ref_mutex);
369         return tape;
370 }
371
372 static void idetape_input_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
373                                   unsigned int bcount)
374 {
375         struct idetape_bh *bh = pc->bh;
376         int count;
377
378         while (bcount) {
379                 if (bh == NULL) {
380                         printk(KERN_ERR "ide-tape: bh == NULL in "
381                                 "idetape_input_buffers\n");
382                         ide_pad_transfer(drive, 0, bcount);
383                         return;
384                 }
385                 count = min(
386                         (unsigned int)(bh->b_size - atomic_read(&bh->b_count)),
387                         bcount);
388                 drive->hwif->tp_ops->input_data(drive, NULL, bh->b_data +
389                                         atomic_read(&bh->b_count), count);
390                 bcount -= count;
391                 atomic_add(count, &bh->b_count);
392                 if (atomic_read(&bh->b_count) == bh->b_size) {
393                         bh = bh->b_reqnext;
394                         if (bh)
395                                 atomic_set(&bh->b_count, 0);
396                 }
397         }
398         pc->bh = bh;
399 }
400
401 static void idetape_output_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
402                                    unsigned int bcount)
403 {
404         struct idetape_bh *bh = pc->bh;
405         int count;
406
407         while (bcount) {
408                 if (bh == NULL) {
409                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
410                                         __func__);
411                         return;
412                 }
413                 count = min((unsigned int)pc->b_count, (unsigned int)bcount);
414                 drive->hwif->tp_ops->output_data(drive, NULL, pc->b_data, count);
415                 bcount -= count;
416                 pc->b_data += count;
417                 pc->b_count -= count;
418                 if (!pc->b_count) {
419                         bh = bh->b_reqnext;
420                         pc->bh = bh;
421                         if (bh) {
422                                 pc->b_data = bh->b_data;
423                                 pc->b_count = atomic_read(&bh->b_count);
424                         }
425                 }
426         }
427 }
428
429 static void idetape_update_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc)
430 {
431         struct idetape_bh *bh = pc->bh;
432         int count;
433         unsigned int bcount = pc->xferred;
434
435         if (pc->flags & PC_FLAG_WRITING)
436                 return;
437         while (bcount) {
438                 if (bh == NULL) {
439                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
440                                         __func__);
441                         return;
442                 }
443                 count = min((unsigned int)bh->b_size, (unsigned int)bcount);
444                 atomic_set(&bh->b_count, count);
445                 if (atomic_read(&bh->b_count) == bh->b_size)
446                         bh = bh->b_reqnext;
447                 bcount -= count;
448         }
449         pc->bh = bh;
450 }
451
452 /*
453  *      idetape_next_pc_storage returns a pointer to a place in which we can
454  *      safely store a packet command, even though we intend to leave the
455  *      driver. A storage space for a maximum of IDETAPE_PC_STACK packet
456  *      commands is allocated at initialization time.
457  */
458 static struct ide_atapi_pc *idetape_next_pc_storage(ide_drive_t *drive)
459 {
460         idetape_tape_t *tape = drive->driver_data;
461
462         debug_log(DBG_PCRQ_STACK, "pc_stack_index=%d\n", tape->pc_stack_index);
463
464         if (tape->pc_stack_index == IDETAPE_PC_STACK)
465                 tape->pc_stack_index = 0;
466         return (&tape->pc_stack[tape->pc_stack_index++]);
467 }
468
469 /*
470  *      idetape_next_rq_storage is used along with idetape_next_pc_storage.
471  *      Since we queue packet commands in the request queue, we need to
472  *      allocate a request, along with the allocation of a packet command.
473  */
474
475 /**************************************************************
476  *                                                            *
477  *  This should get fixed to use kmalloc(.., GFP_ATOMIC)      *
478  *  followed later on by kfree().   -ml                       *
479  *                                                            *
480  **************************************************************/
481
482 static struct request *idetape_next_rq_storage(ide_drive_t *drive)
483 {
484         idetape_tape_t *tape = drive->driver_data;
485
486         debug_log(DBG_PCRQ_STACK, "rq_stack_index=%d\n", tape->rq_stack_index);
487
488         if (tape->rq_stack_index == IDETAPE_PC_STACK)
489                 tape->rq_stack_index = 0;
490         return (&tape->rq_stack[tape->rq_stack_index++]);
491 }
492
493 /*
494  * called on each failed packet command retry to analyze the request sense. We
495  * currently do not utilize this information.
496  */
497 static void idetape_analyze_error(ide_drive_t *drive, u8 *sense)
498 {
499         idetape_tape_t *tape = drive->driver_data;
500         struct ide_atapi_pc *pc = tape->failed_pc;
501
502         tape->sense_key = sense[2] & 0xF;
503         tape->asc       = sense[12];
504         tape->ascq      = sense[13];
505
506         debug_log(DBG_ERR, "pc = %x, sense key = %x, asc = %x, ascq = %x\n",
507                  pc->c[0], tape->sense_key, tape->asc, tape->ascq);
508
509         /* Correct pc->xferred by asking the tape.       */
510         if (pc->flags & PC_FLAG_DMA_ERROR) {
511                 pc->xferred = pc->req_xfer -
512                         tape->blk_size *
513                         get_unaligned_be32(&sense[3]);
514                 idetape_update_buffers(drive, pc);
515         }
516
517         /*
518          * If error was the result of a zero-length read or write command,
519          * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
520          * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
521          */
522         if ((pc->c[0] == READ_6 || pc->c[0] == WRITE_6)
523             /* length == 0 */
524             && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
525                 if (tape->sense_key == 5) {
526                         /* don't report an error, everything's ok */
527                         pc->error = 0;
528                         /* don't retry read/write */
529                         pc->flags |= PC_FLAG_ABORT;
530                 }
531         }
532         if (pc->c[0] == READ_6 && (sense[2] & 0x80)) {
533                 pc->error = IDETAPE_ERROR_FILEMARK;
534                 pc->flags |= PC_FLAG_ABORT;
535         }
536         if (pc->c[0] == WRITE_6) {
537                 if ((sense[2] & 0x40) || (tape->sense_key == 0xd
538                      && tape->asc == 0x0 && tape->ascq == 0x2)) {
539                         pc->error = IDETAPE_ERROR_EOD;
540                         pc->flags |= PC_FLAG_ABORT;
541                 }
542         }
543         if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
544                 if (tape->sense_key == 8) {
545                         pc->error = IDETAPE_ERROR_EOD;
546                         pc->flags |= PC_FLAG_ABORT;
547                 }
548                 if (!(pc->flags & PC_FLAG_ABORT) &&
549                     pc->xferred)
550                         pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
551         }
552 }
553
554 /* Free data buffers completely. */
555 static void ide_tape_kfree_buffer(idetape_tape_t *tape)
556 {
557         struct idetape_bh *prev_bh, *bh = tape->merge_bh;
558
559         while (bh) {
560                 u32 size = bh->b_size;
561
562                 while (size) {
563                         unsigned int order = fls(size >> PAGE_SHIFT)-1;
564
565                         if (bh->b_data)
566                                 free_pages((unsigned long)bh->b_data, order);
567
568                         size &= (order-1);
569                         bh->b_data += (1 << order) * PAGE_SIZE;
570                 }
571                 prev_bh = bh;
572                 bh = bh->b_reqnext;
573                 kfree(prev_bh);
574         }
575 }
576
577 static int idetape_end_request(ide_drive_t *drive, int uptodate, int nr_sects)
578 {
579         struct request *rq = HWGROUP(drive)->rq;
580         idetape_tape_t *tape = drive->driver_data;
581         unsigned long flags;
582         int error;
583
584         debug_log(DBG_PROCS, "Enter %s\n", __func__);
585
586         switch (uptodate) {
587         case 0: error = IDETAPE_ERROR_GENERAL; break;
588         case 1: error = 0; break;
589         default: error = uptodate;
590         }
591         rq->errors = error;
592         if (error)
593                 tape->failed_pc = NULL;
594
595         if (!blk_special_request(rq)) {
596                 ide_end_request(drive, uptodate, nr_sects);
597                 return 0;
598         }
599
600         spin_lock_irqsave(&tape->lock, flags);
601
602         ide_end_drive_cmd(drive, 0, 0);
603
604         spin_unlock_irqrestore(&tape->lock, flags);
605         return 0;
606 }
607
608 static void ide_tape_callback(ide_drive_t *drive)
609 {
610         idetape_tape_t *tape = drive->driver_data;
611         struct ide_atapi_pc *pc = tape->pc;
612         int uptodate = pc->error ? 0 : 1;
613
614         debug_log(DBG_PROCS, "Enter %s\n", __func__);
615
616         if (tape->failed_pc == pc)
617                 tape->failed_pc = NULL;
618
619         if (pc->c[0] == REQUEST_SENSE) {
620                 if (uptodate)
621                         idetape_analyze_error(drive, pc->buf);
622                 else
623                         printk(KERN_ERR "ide-tape: Error in REQUEST SENSE "
624                                         "itself - Aborting request!\n");
625         } else if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
626                 struct request *rq = drive->hwif->hwgroup->rq;
627                 int blocks = pc->xferred / tape->blk_size;
628
629                 tape->avg_size += blocks * tape->blk_size;
630
631                 if (time_after_eq(jiffies, tape->avg_time + HZ)) {
632                         tape->avg_speed = tape->avg_size * HZ /
633                                 (jiffies - tape->avg_time) / 1024;
634                         tape->avg_size = 0;
635                         tape->avg_time = jiffies;
636                 }
637
638                 tape->first_frame += blocks;
639                 rq->current_nr_sectors -= blocks;
640
641                 if (pc->error)
642                         uptodate = pc->error;
643         } else if (pc->c[0] == READ_POSITION && uptodate) {
644                 u8 *readpos = tape->pc->buf;
645
646                 debug_log(DBG_SENSE, "BOP - %s\n",
647                                 (readpos[0] & 0x80) ? "Yes" : "No");
648                 debug_log(DBG_SENSE, "EOP - %s\n",
649                                 (readpos[0] & 0x40) ? "Yes" : "No");
650
651                 if (readpos[0] & 0x4) {
652                         printk(KERN_INFO "ide-tape: Block location is unknown"
653                                          "to the tape\n");
654                         clear_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags);
655                         uptodate = 0;
656                 } else {
657                         debug_log(DBG_SENSE, "Block Location - %u\n",
658                                         be32_to_cpup((__be32 *)&readpos[4]));
659
660                         tape->partition = readpos[1];
661                         tape->first_frame = be32_to_cpup((__be32 *)&readpos[4]);
662                         set_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags);
663                 }
664         }
665
666         idetape_end_request(drive, uptodate, 0);
667 }
668
669 static void idetape_init_pc(struct ide_atapi_pc *pc)
670 {
671         memset(pc->c, 0, 12);
672         pc->retries = 0;
673         pc->flags = 0;
674         pc->req_xfer = 0;
675         pc->buf = pc->pc_buf;
676         pc->buf_size = IDETAPE_PC_BUFFER_SIZE;
677         pc->bh = NULL;
678         pc->b_data = NULL;
679 }
680
681 static void idetape_create_request_sense_cmd(struct ide_atapi_pc *pc)
682 {
683         idetape_init_pc(pc);
684         pc->c[0] = REQUEST_SENSE;
685         pc->c[4] = 20;
686         pc->req_xfer = 20;
687 }
688
689 static void idetape_init_rq(struct request *rq, u8 cmd)
690 {
691         blk_rq_init(NULL, rq);
692         rq->cmd_type = REQ_TYPE_SPECIAL;
693         rq->cmd[13] = cmd;
694 }
695
696 /*
697  * Generate a new packet command request in front of the request queue, before
698  * the current request, so that it will be processed immediately, on the next
699  * pass through the driver. The function below is called from the request
700  * handling part of the driver (the "bottom" part). Safe storage for the request
701  * should be allocated with ide_tape_next_{pc,rq}_storage() prior to that.
702  *
703  * Memory for those requests is pre-allocated at initialization time, and is
704  * limited to IDETAPE_PC_STACK requests. We assume that we have enough space for
705  * the maximum possible number of inter-dependent packet commands.
706  *
707  * The higher level of the driver - The ioctl handler and the character device
708  * handling functions should queue request to the lower level part and wait for
709  * their completion using idetape_queue_pc_tail or idetape_queue_rw_tail.
710  */
711 static void idetape_queue_pc_head(ide_drive_t *drive, struct ide_atapi_pc *pc,
712                                   struct request *rq)
713 {
714         struct ide_tape_obj *tape = drive->driver_data;
715
716         idetape_init_rq(rq, REQ_IDETAPE_PC1);
717         rq->cmd_flags |= REQ_PREEMPT;
718         rq->buffer = (char *) pc;
719         rq->rq_disk = tape->disk;
720         memcpy(rq->cmd, pc->c, 12);
721         ide_do_drive_cmd(drive, rq);
722 }
723
724 /*
725  *      idetape_retry_pc is called when an error was detected during the
726  *      last packet command. We queue a request sense packet command in
727  *      the head of the request list.
728  */
729 static void idetape_retry_pc(ide_drive_t *drive)
730 {
731         struct ide_atapi_pc *pc;
732         struct request *rq;
733
734         (void)ide_read_error(drive);
735         pc = idetape_next_pc_storage(drive);
736         rq = idetape_next_rq_storage(drive);
737         idetape_create_request_sense_cmd(pc);
738         set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
739         idetape_queue_pc_head(drive, pc, rq);
740 }
741
742 /*
743  * Postpone the current request so that ide.c will be able to service requests
744  * from another device on the same hwgroup while we are polling for DSC.
745  */
746 static void idetape_postpone_request(ide_drive_t *drive)
747 {
748         idetape_tape_t *tape = drive->driver_data;
749
750         debug_log(DBG_PROCS, "Enter %s\n", __func__);
751
752         tape->postponed_rq = HWGROUP(drive)->rq;
753         ide_stall_queue(drive, tape->dsc_poll_freq);
754 }
755
756 static void ide_tape_handle_dsc(ide_drive_t *drive)
757 {
758         idetape_tape_t *tape = drive->driver_data;
759
760         /* Media access command */
761         tape->dsc_polling_start = jiffies;
762         tape->dsc_poll_freq = IDETAPE_DSC_MA_FAST;
763         tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
764         /* Allow ide.c to handle other requests */
765         idetape_postpone_request(drive);
766 }
767
768 static void ide_tape_io_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
769                                 unsigned int bcount, int write)
770 {
771         if (write)
772                 idetape_output_buffers(drive, pc, bcount);
773         else
774                 idetape_input_buffers(drive, pc, bcount);
775 }
776
777 /*
778  * This is the usual interrupt handler which will be called during a packet
779  * command. We will transfer some of the data (as requested by the drive) and
780  * will re-point interrupt handler to us. When data transfer is finished, we
781  * will act according to the algorithm described before
782  * idetape_issue_pc.
783  */
784 static ide_startstop_t idetape_pc_intr(ide_drive_t *drive)
785 {
786         idetape_tape_t *tape = drive->driver_data;
787
788         return ide_pc_intr(drive, tape->pc, idetape_pc_intr, IDETAPE_WAIT_CMD,
789                            NULL, idetape_update_buffers, idetape_retry_pc,
790                            ide_tape_handle_dsc, ide_tape_io_buffers);
791 }
792
793 /*
794  * Packet Command Interface
795  *
796  * The current Packet Command is available in tape->pc, and will not change
797  * until we finish handling it. Each packet command is associated with a
798  * callback function that will be called when the command is finished.
799  *
800  * The handling will be done in three stages:
801  *
802  * 1. idetape_issue_pc will send the packet command to the drive, and will set
803  * the interrupt handler to idetape_pc_intr.
804  *
805  * 2. On each interrupt, idetape_pc_intr will be called. This step will be
806  * repeated until the device signals us that no more interrupts will be issued.
807  *
808  * 3. ATAPI Tape media access commands have immediate status with a delayed
809  * process. In case of a successful initiation of a media access packet command,
810  * the DSC bit will be set when the actual execution of the command is finished.
811  * Since the tape drive will not issue an interrupt, we have to poll for this
812  * event. In this case, we define the request as "low priority request" by
813  * setting rq_status to IDETAPE_RQ_POSTPONED, set a timer to poll for DSC and
814  * exit the driver.
815  *
816  * ide.c will then give higher priority to requests which originate from the
817  * other device, until will change rq_status to RQ_ACTIVE.
818  *
819  * 4. When the packet command is finished, it will be checked for errors.
820  *
821  * 5. In case an error was found, we queue a request sense packet command in
822  * front of the request queue and retry the operation up to
823  * IDETAPE_MAX_PC_RETRIES times.
824  *
825  * 6. In case no error was found, or we decided to give up and not to retry
826  * again, the callback function will be called and then we will handle the next
827  * request.
828  */
829 static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
830 {
831         idetape_tape_t *tape = drive->driver_data;
832
833         return ide_transfer_pc(drive, tape->pc, idetape_pc_intr,
834                                IDETAPE_WAIT_CMD, NULL);
835 }
836
837 static ide_startstop_t idetape_issue_pc(ide_drive_t *drive,
838                 struct ide_atapi_pc *pc)
839 {
840         idetape_tape_t *tape = drive->driver_data;
841
842         if (tape->pc->c[0] == REQUEST_SENSE &&
843             pc->c[0] == REQUEST_SENSE) {
844                 printk(KERN_ERR "ide-tape: possible ide-tape.c bug - "
845                         "Two request sense in serial were issued\n");
846         }
847
848         if (tape->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
849                 tape->failed_pc = pc;
850         /* Set the current packet command */
851         tape->pc = pc;
852
853         if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
854                 (pc->flags & PC_FLAG_ABORT)) {
855                 /*
856                  * We will "abort" retrying a packet command in case legitimate
857                  * error code was received (crossing a filemark, or end of the
858                  * media, for example).
859                  */
860                 if (!(pc->flags & PC_FLAG_ABORT)) {
861                         if (!(pc->c[0] == TEST_UNIT_READY &&
862                               tape->sense_key == 2 && tape->asc == 4 &&
863                              (tape->ascq == 1 || tape->ascq == 8))) {
864                                 printk(KERN_ERR "ide-tape: %s: I/O error, "
865                                                 "pc = %2x, key = %2x, "
866                                                 "asc = %2x, ascq = %2x\n",
867                                                 tape->name, pc->c[0],
868                                                 tape->sense_key, tape->asc,
869                                                 tape->ascq);
870                         }
871                         /* Giving up */
872                         pc->error = IDETAPE_ERROR_GENERAL;
873                 }
874                 tape->failed_pc = NULL;
875                 drive->pc_callback(drive);
876                 return ide_stopped;
877         }
878         debug_log(DBG_SENSE, "Retry #%d, cmd = %02X\n", pc->retries, pc->c[0]);
879
880         pc->retries++;
881
882         return ide_issue_pc(drive, pc, idetape_transfer_pc,
883                             IDETAPE_WAIT_CMD, NULL);
884 }
885
886 /* A mode sense command is used to "sense" tape parameters. */
887 static void idetape_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
888 {
889         idetape_init_pc(pc);
890         pc->c[0] = MODE_SENSE;
891         if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
892                 /* DBD = 1 - Don't return block descriptors */
893                 pc->c[1] = 8;
894         pc->c[2] = page_code;
895         /*
896          * Changed pc->c[3] to 0 (255 will at best return unused info).
897          *
898          * For SCSI this byte is defined as subpage instead of high byte
899          * of length and some IDE drives seem to interpret it this way
900          * and return an error when 255 is used.
901          */
902         pc->c[3] = 0;
903         /* We will just discard data in that case */
904         pc->c[4] = 255;
905         if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
906                 pc->req_xfer = 12;
907         else if (page_code == IDETAPE_CAPABILITIES_PAGE)
908                 pc->req_xfer = 24;
909         else
910                 pc->req_xfer = 50;
911 }
912
913 static ide_startstop_t idetape_media_access_finished(ide_drive_t *drive)
914 {
915         ide_hwif_t *hwif = drive->hwif;
916         idetape_tape_t *tape = drive->driver_data;
917         struct ide_atapi_pc *pc = tape->pc;
918         u8 stat;
919
920         stat = hwif->tp_ops->read_status(hwif);
921
922         if (stat & SEEK_STAT) {
923                 if (stat & ERR_STAT) {
924                         /* Error detected */
925                         if (pc->c[0] != TEST_UNIT_READY)
926                                 printk(KERN_ERR "ide-tape: %s: I/O error, ",
927                                                 tape->name);
928                         /* Retry operation */
929                         idetape_retry_pc(drive);
930                         return ide_stopped;
931                 }
932                 pc->error = 0;
933         } else {
934                 pc->error = IDETAPE_ERROR_GENERAL;
935                 tape->failed_pc = NULL;
936         }
937         drive->pc_callback(drive);
938         return ide_stopped;
939 }
940
941 static void ide_tape_create_rw_cmd(idetape_tape_t *tape,
942                                    struct ide_atapi_pc *pc, struct request *rq,
943                                    u8 opcode)
944 {
945         struct idetape_bh *bh = (struct idetape_bh *)rq->special;
946         unsigned int length = rq->current_nr_sectors;
947
948         idetape_init_pc(pc);
949         put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
950         pc->c[1] = 1;
951         pc->bh = bh;
952         pc->buf = NULL;
953         pc->buf_size = length * tape->blk_size;
954         pc->req_xfer = pc->buf_size;
955         if (pc->req_xfer == tape->buffer_size)
956                 pc->flags |= PC_FLAG_DMA_OK;
957
958         if (opcode == READ_6) {
959                 pc->c[0] = READ_6;
960                 atomic_set(&bh->b_count, 0);
961         } else if (opcode == WRITE_6) {
962                 pc->c[0] = WRITE_6;
963                 pc->flags |= PC_FLAG_WRITING;
964                 pc->b_data = bh->b_data;
965                 pc->b_count = atomic_read(&bh->b_count);
966         }
967
968         memcpy(rq->cmd, pc->c, 12);
969 }
970
971 static ide_startstop_t idetape_do_request(ide_drive_t *drive,
972                                           struct request *rq, sector_t block)
973 {
974         ide_hwif_t *hwif = drive->hwif;
975         idetape_tape_t *tape = drive->driver_data;
976         struct ide_atapi_pc *pc = NULL;
977         struct request *postponed_rq = tape->postponed_rq;
978         u8 stat;
979
980         debug_log(DBG_SENSE, "sector: %ld, nr_sectors: %ld,"
981                         " current_nr_sectors: %d\n",
982                         rq->sector, rq->nr_sectors, rq->current_nr_sectors);
983
984         if (!blk_special_request(rq)) {
985                 /* We do not support buffer cache originated requests. */
986                 printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
987                         "request queue (%d)\n", drive->name, rq->cmd_type);
988                 ide_end_request(drive, 0, 0);
989                 return ide_stopped;
990         }
991
992         /* Retry a failed packet command */
993         if (tape->failed_pc && tape->pc->c[0] == REQUEST_SENSE) {
994                 pc = tape->failed_pc;
995                 goto out;
996         }
997
998         if (postponed_rq != NULL)
999                 if (rq != postponed_rq) {
1000                         printk(KERN_ERR "ide-tape: ide-tape.c bug - "
1001                                         "Two DSC requests were queued\n");
1002                         idetape_end_request(drive, 0, 0);
1003                         return ide_stopped;
1004                 }
1005
1006         tape->postponed_rq = NULL;
1007
1008         /*
1009          * If the tape is still busy, postpone our request and service
1010          * the other device meanwhile.
1011          */
1012         stat = hwif->tp_ops->read_status(hwif);
1013
1014         if (!drive->dsc_overlap && !(rq->cmd[13] & REQ_IDETAPE_PC2))
1015                 set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
1016
1017         if (drive->post_reset == 1) {
1018                 set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
1019                 drive->post_reset = 0;
1020         }
1021
1022         if (!test_and_clear_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags) &&
1023             (stat & SEEK_STAT) == 0) {
1024                 if (postponed_rq == NULL) {
1025                         tape->dsc_polling_start = jiffies;
1026                         tape->dsc_poll_freq = tape->best_dsc_rw_freq;
1027                         tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
1028                 } else if (time_after(jiffies, tape->dsc_timeout)) {
1029                         printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
1030                                 tape->name);
1031                         if (rq->cmd[13] & REQ_IDETAPE_PC2) {
1032                                 idetape_media_access_finished(drive);
1033                                 return ide_stopped;
1034                         } else {
1035                                 return ide_do_reset(drive);
1036                         }
1037                 } else if (time_after(jiffies,
1038                                         tape->dsc_polling_start +
1039                                         IDETAPE_DSC_MA_THRESHOLD))
1040                         tape->dsc_poll_freq = IDETAPE_DSC_MA_SLOW;
1041                 idetape_postpone_request(drive);
1042                 return ide_stopped;
1043         }
1044         if (rq->cmd[13] & REQ_IDETAPE_READ) {
1045                 pc = idetape_next_pc_storage(drive);
1046                 ide_tape_create_rw_cmd(tape, pc, rq, READ_6);
1047                 goto out;
1048         }
1049         if (rq->cmd[13] & REQ_IDETAPE_WRITE) {
1050                 pc = idetape_next_pc_storage(drive);
1051                 ide_tape_create_rw_cmd(tape, pc, rq, WRITE_6);
1052                 goto out;
1053         }
1054         if (rq->cmd[13] & REQ_IDETAPE_PC1) {
1055                 pc = (struct ide_atapi_pc *) rq->buffer;
1056                 rq->cmd[13] &= ~(REQ_IDETAPE_PC1);
1057                 rq->cmd[13] |= REQ_IDETAPE_PC2;
1058                 goto out;
1059         }
1060         if (rq->cmd[13] & REQ_IDETAPE_PC2) {
1061                 idetape_media_access_finished(drive);
1062                 return ide_stopped;
1063         }
1064         BUG();
1065
1066 out:
1067         return idetape_issue_pc(drive, pc);
1068 }
1069
1070 /*
1071  * The function below uses __get_free_pages to allocate a data buffer of size
1072  * tape->buffer_size (or a bit more). We attempt to combine sequential pages as
1073  * much as possible.
1074  *
1075  * It returns a pointer to the newly allocated buffer, or NULL in case of
1076  * failure.
1077  */
1078 static struct idetape_bh *ide_tape_kmalloc_buffer(idetape_tape_t *tape,
1079                                                   int full, int clear)
1080 {
1081         struct idetape_bh *prev_bh, *bh, *merge_bh;
1082         int pages = tape->pages_per_buffer;
1083         unsigned int order, b_allocd;
1084         char *b_data = NULL;
1085
1086         merge_bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
1087         bh = merge_bh;
1088         if (bh == NULL)
1089                 goto abort;
1090
1091         order = fls(pages) - 1;
1092         bh->b_data = (char *) __get_free_pages(GFP_KERNEL, order);
1093         if (!bh->b_data)
1094                 goto abort;
1095         b_allocd = (1 << order) * PAGE_SIZE;
1096         pages &= (order-1);
1097
1098         if (clear)
1099                 memset(bh->b_data, 0, b_allocd);
1100         bh->b_reqnext = NULL;
1101         bh->b_size = b_allocd;
1102         atomic_set(&bh->b_count, full ? bh->b_size : 0);
1103
1104         while (pages) {
1105                 order = fls(pages) - 1;
1106                 b_data = (char *) __get_free_pages(GFP_KERNEL, order);
1107                 if (!b_data)
1108                         goto abort;
1109                 b_allocd = (1 << order) * PAGE_SIZE;
1110
1111                 if (clear)
1112                         memset(b_data, 0, b_allocd);
1113
1114                 /* newly allocated page frames below buffer header or ...*/
1115                 if (bh->b_data == b_data + b_allocd) {
1116                         bh->b_size += b_allocd;
1117                         bh->b_data -= b_allocd;
1118                         if (full)
1119                                 atomic_add(b_allocd, &bh->b_count);
1120                         continue;
1121                 }
1122                 /* they are above the header */
1123                 if (b_data == bh->b_data + bh->b_size) {
1124                         bh->b_size += b_allocd;
1125                         if (full)
1126                                 atomic_add(b_allocd, &bh->b_count);
1127                         continue;
1128                 }
1129                 prev_bh = bh;
1130                 bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
1131                 if (!bh) {
1132                         free_pages((unsigned long) b_data, order);
1133                         goto abort;
1134                 }
1135                 bh->b_reqnext = NULL;
1136                 bh->b_data = b_data;
1137                 bh->b_size = b_allocd;
1138                 atomic_set(&bh->b_count, full ? bh->b_size : 0);
1139                 prev_bh->b_reqnext = bh;
1140
1141                 pages &= (order-1);
1142         }
1143
1144         bh->b_size -= tape->excess_bh_size;
1145         if (full)
1146                 atomic_sub(tape->excess_bh_size, &bh->b_count);
1147         return merge_bh;
1148 abort:
1149         ide_tape_kfree_buffer(tape);
1150         return NULL;
1151 }
1152
1153 static int idetape_copy_stage_from_user(idetape_tape_t *tape,
1154                                         const char __user *buf, int n)
1155 {
1156         struct idetape_bh *bh = tape->bh;
1157         int count;
1158         int ret = 0;
1159
1160         while (n) {
1161                 if (bh == NULL) {
1162                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
1163                                         __func__);
1164                         return 1;
1165                 }
1166                 count = min((unsigned int)
1167                                 (bh->b_size - atomic_read(&bh->b_count)),
1168                                 (unsigned int)n);
1169                 if (copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf,
1170                                 count))
1171                         ret = 1;
1172                 n -= count;
1173                 atomic_add(count, &bh->b_count);
1174                 buf += count;
1175                 if (atomic_read(&bh->b_count) == bh->b_size) {
1176                         bh = bh->b_reqnext;
1177                         if (bh)
1178                                 atomic_set(&bh->b_count, 0);
1179                 }
1180         }
1181         tape->bh = bh;
1182         return ret;
1183 }
1184
1185 static int idetape_copy_stage_to_user(idetape_tape_t *tape, char __user *buf,
1186                                       int n)
1187 {
1188         struct idetape_bh *bh = tape->bh;
1189         int count;
1190         int ret = 0;
1191
1192         while (n) {
1193                 if (bh == NULL) {
1194                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
1195                                         __func__);
1196                         return 1;
1197                 }
1198                 count = min(tape->b_count, n);
1199                 if  (copy_to_user(buf, tape->b_data, count))
1200                         ret = 1;
1201                 n -= count;
1202                 tape->b_data += count;
1203                 tape->b_count -= count;
1204                 buf += count;
1205                 if (!tape->b_count) {
1206                         bh = bh->b_reqnext;
1207                         tape->bh = bh;
1208                         if (bh) {
1209                                 tape->b_data = bh->b_data;
1210                                 tape->b_count = atomic_read(&bh->b_count);
1211                         }
1212                 }
1213         }
1214         return ret;
1215 }
1216
1217 static void idetape_init_merge_buffer(idetape_tape_t *tape)
1218 {
1219         struct idetape_bh *bh = tape->merge_bh;
1220         tape->bh = tape->merge_bh;
1221
1222         if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
1223                 atomic_set(&bh->b_count, 0);
1224         else {
1225                 tape->b_data = bh->b_data;
1226                 tape->b_count = atomic_read(&bh->b_count);
1227         }
1228 }
1229
1230 /*
1231  * Write a filemark if write_filemark=1. Flush the device buffers without
1232  * writing a filemark otherwise.
1233  */
1234 static void idetape_create_write_filemark_cmd(ide_drive_t *drive,
1235                 struct ide_atapi_pc *pc, int write_filemark)
1236 {
1237         idetape_init_pc(pc);
1238         pc->c[0] = WRITE_FILEMARKS;
1239         pc->c[4] = write_filemark;
1240         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1241 }
1242
1243 static void idetape_create_test_unit_ready_cmd(struct ide_atapi_pc *pc)
1244 {
1245         idetape_init_pc(pc);
1246         pc->c[0] = TEST_UNIT_READY;
1247 }
1248
1249 /*
1250  * We add a special packet command request to the tail of the request queue, and
1251  * wait for it to be serviced. This is not to be called from within the request
1252  * handling part of the driver! We allocate here data on the stack and it is
1253  * valid until the request is finished. This is not the case for the bottom part
1254  * of the driver, where we are always leaving the functions to wait for an
1255  * interrupt or a timer event.
1256  *
1257  * From the bottom part of the driver, we should allocate safe memory using
1258  * idetape_next_pc_storage() and ide_tape_next_rq_storage(), and add the request
1259  * to the request list without waiting for it to be serviced! In that case, we
1260  * usually use idetape_queue_pc_head().
1261  */
1262 static int idetape_queue_pc_tail(ide_drive_t *drive, struct ide_atapi_pc *pc)
1263 {
1264         struct ide_tape_obj *tape = drive->driver_data;
1265         struct request *rq;
1266         int error;
1267
1268         rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
1269         rq->cmd_type = REQ_TYPE_SPECIAL;
1270         rq->cmd[13] = REQ_IDETAPE_PC1;
1271         rq->buffer = (char *)pc;
1272         memcpy(rq->cmd, pc->c, 12);
1273         error = blk_execute_rq(drive->queue, tape->disk, rq, 0);
1274         blk_put_request(rq);
1275         return error;
1276 }
1277
1278 static void idetape_create_load_unload_cmd(ide_drive_t *drive,
1279                 struct ide_atapi_pc *pc, int cmd)
1280 {
1281         idetape_init_pc(pc);
1282         pc->c[0] = START_STOP;
1283         pc->c[4] = cmd;
1284         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1285 }
1286
1287 static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
1288 {
1289         idetape_tape_t *tape = drive->driver_data;
1290         struct ide_atapi_pc pc;
1291         int load_attempted = 0;
1292
1293         /* Wait for the tape to become ready */
1294         set_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags);
1295         timeout += jiffies;
1296         while (time_before(jiffies, timeout)) {
1297                 idetape_create_test_unit_ready_cmd(&pc);
1298                 if (!idetape_queue_pc_tail(drive, &pc))
1299                         return 0;
1300                 if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
1301                     || (tape->asc == 0x3A)) {
1302                         /* no media */
1303                         if (load_attempted)
1304                                 return -ENOMEDIUM;
1305                         idetape_create_load_unload_cmd(drive, &pc,
1306                                                         IDETAPE_LU_LOAD_MASK);
1307                         idetape_queue_pc_tail(drive, &pc);
1308                         load_attempted = 1;
1309                 /* not about to be ready */
1310                 } else if (!(tape->sense_key == 2 && tape->asc == 4 &&
1311                              (tape->ascq == 1 || tape->ascq == 8)))
1312                         return -EIO;
1313                 msleep(100);
1314         }
1315         return -EIO;
1316 }
1317
1318 static int idetape_flush_tape_buffers(ide_drive_t *drive)
1319 {
1320         struct ide_atapi_pc pc;
1321         int rc;
1322
1323         idetape_create_write_filemark_cmd(drive, &pc, 0);
1324         rc = idetape_queue_pc_tail(drive, &pc);
1325         if (rc)
1326                 return rc;
1327         idetape_wait_ready(drive, 60 * 5 * HZ);
1328         return 0;
1329 }
1330
1331 static void idetape_create_read_position_cmd(struct ide_atapi_pc *pc)
1332 {
1333         idetape_init_pc(pc);
1334         pc->c[0] = READ_POSITION;
1335         pc->req_xfer = 20;
1336 }
1337
1338 static int idetape_read_position(ide_drive_t *drive)
1339 {
1340         idetape_tape_t *tape = drive->driver_data;
1341         struct ide_atapi_pc pc;
1342         int position;
1343
1344         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1345
1346         idetape_create_read_position_cmd(&pc);
1347         if (idetape_queue_pc_tail(drive, &pc))
1348                 return -1;
1349         position = tape->first_frame;
1350         return position;
1351 }
1352
1353 static void idetape_create_locate_cmd(ide_drive_t *drive,
1354                 struct ide_atapi_pc *pc,
1355                 unsigned int block, u8 partition, int skip)
1356 {
1357         idetape_init_pc(pc);
1358         pc->c[0] = POSITION_TO_ELEMENT;
1359         pc->c[1] = 2;
1360         put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[3]);
1361         pc->c[8] = partition;
1362         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1363 }
1364
1365 static int idetape_create_prevent_cmd(ide_drive_t *drive,
1366                 struct ide_atapi_pc *pc, int prevent)
1367 {
1368         idetape_tape_t *tape = drive->driver_data;
1369
1370         /* device supports locking according to capabilities page */
1371         if (!(tape->caps[6] & 0x01))
1372                 return 0;
1373
1374         idetape_init_pc(pc);
1375         pc->c[0] = ALLOW_MEDIUM_REMOVAL;
1376         pc->c[4] = prevent;
1377         return 1;
1378 }
1379
1380 static void __ide_tape_discard_merge_buffer(ide_drive_t *drive)
1381 {
1382         idetape_tape_t *tape = drive->driver_data;
1383
1384         if (tape->chrdev_dir != IDETAPE_DIR_READ)
1385                 return;
1386
1387         clear_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags);
1388         tape->merge_bh_size = 0;
1389         if (tape->merge_bh != NULL) {
1390                 ide_tape_kfree_buffer(tape);
1391                 tape->merge_bh = NULL;
1392         }
1393
1394         tape->chrdev_dir = IDETAPE_DIR_NONE;
1395 }
1396
1397 /*
1398  * Position the tape to the requested block using the LOCATE packet command.
1399  * A READ POSITION command is then issued to check where we are positioned. Like
1400  * all higher level operations, we queue the commands at the tail of the request
1401  * queue and wait for their completion.
1402  */
1403 static int idetape_position_tape(ide_drive_t *drive, unsigned int block,
1404                 u8 partition, int skip)
1405 {
1406         idetape_tape_t *tape = drive->driver_data;
1407         int retval;
1408         struct ide_atapi_pc pc;
1409
1410         if (tape->chrdev_dir == IDETAPE_DIR_READ)
1411                 __ide_tape_discard_merge_buffer(drive);
1412         idetape_wait_ready(drive, 60 * 5 * HZ);
1413         idetape_create_locate_cmd(drive, &pc, block, partition, skip);
1414         retval = idetape_queue_pc_tail(drive, &pc);
1415         if (retval)
1416                 return (retval);
1417
1418         idetape_create_read_position_cmd(&pc);
1419         return (idetape_queue_pc_tail(drive, &pc));
1420 }
1421
1422 static void ide_tape_discard_merge_buffer(ide_drive_t *drive,
1423                                           int restore_position)
1424 {
1425         idetape_tape_t *tape = drive->driver_data;
1426         int seek, position;
1427
1428         __ide_tape_discard_merge_buffer(drive);
1429         if (restore_position) {
1430                 position = idetape_read_position(drive);
1431                 seek = position > 0 ? position : 0;
1432                 if (idetape_position_tape(drive, seek, 0, 0)) {
1433                         printk(KERN_INFO "ide-tape: %s: position_tape failed in"
1434                                          " %s\n", tape->name, __func__);
1435                         return;
1436                 }
1437         }
1438 }
1439
1440 /*
1441  * Generate a read/write request for the block device interface and wait for it
1442  * to be serviced.
1443  */
1444 static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks,
1445                                  struct idetape_bh *bh)
1446 {
1447         idetape_tape_t *tape = drive->driver_data;
1448         struct request *rq;
1449         int ret, errors;
1450
1451         debug_log(DBG_SENSE, "%s: cmd=%d\n", __func__, cmd);
1452
1453         rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
1454         rq->cmd_type = REQ_TYPE_SPECIAL;
1455         rq->cmd[13] = cmd;
1456         rq->rq_disk = tape->disk;
1457         rq->special = (void *)bh;
1458         rq->sector = tape->first_frame;
1459         rq->nr_sectors = blocks;
1460         rq->current_nr_sectors = blocks;
1461         blk_execute_rq(drive->queue, tape->disk, rq, 0);
1462
1463         errors = rq->errors;
1464         ret = tape->blk_size * (blocks - rq->current_nr_sectors);
1465         blk_put_request(rq);
1466
1467         if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
1468                 return 0;
1469
1470         if (tape->merge_bh)
1471                 idetape_init_merge_buffer(tape);
1472         if (errors == IDETAPE_ERROR_GENERAL)
1473                 return -EIO;
1474         return ret;
1475 }
1476
1477 static void idetape_create_inquiry_cmd(struct ide_atapi_pc *pc)
1478 {
1479         idetape_init_pc(pc);
1480         pc->c[0] = INQUIRY;
1481         pc->c[4] = 254;
1482         pc->req_xfer = 254;
1483 }
1484
1485 static void idetape_create_rewind_cmd(ide_drive_t *drive,
1486                 struct ide_atapi_pc *pc)
1487 {
1488         idetape_init_pc(pc);
1489         pc->c[0] = REZERO_UNIT;
1490         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1491 }
1492
1493 static void idetape_create_erase_cmd(struct ide_atapi_pc *pc)
1494 {
1495         idetape_init_pc(pc);
1496         pc->c[0] = ERASE;
1497         pc->c[1] = 1;
1498         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1499 }
1500
1501 static void idetape_create_space_cmd(struct ide_atapi_pc *pc, int count, u8 cmd)
1502 {
1503         idetape_init_pc(pc);
1504         pc->c[0] = SPACE;
1505         put_unaligned(cpu_to_be32(count), (unsigned int *) &pc->c[1]);
1506         pc->c[1] = cmd;
1507         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1508 }
1509
1510 /* Queue up a character device originated write request. */
1511 static int idetape_add_chrdev_write_request(ide_drive_t *drive, int blocks)
1512 {
1513         idetape_tape_t *tape = drive->driver_data;
1514
1515         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1516
1517         return idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE,
1518                                      blocks, tape->merge_bh);
1519 }
1520
1521 static void ide_tape_flush_merge_buffer(ide_drive_t *drive)
1522 {
1523         idetape_tape_t *tape = drive->driver_data;
1524         int blocks, min;
1525         struct idetape_bh *bh;
1526
1527         if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
1528                 printk(KERN_ERR "ide-tape: bug: Trying to empty merge buffer"
1529                                 " but we are not writing.\n");
1530                 return;
1531         }
1532         if (tape->merge_bh_size > tape->buffer_size) {
1533                 printk(KERN_ERR "ide-tape: bug: merge_buffer too big\n");
1534                 tape->merge_bh_size = tape->buffer_size;
1535         }
1536         if (tape->merge_bh_size) {
1537                 blocks = tape->merge_bh_size / tape->blk_size;
1538                 if (tape->merge_bh_size % tape->blk_size) {
1539                         unsigned int i;
1540
1541                         blocks++;
1542                         i = tape->blk_size - tape->merge_bh_size %
1543                                 tape->blk_size;
1544                         bh = tape->bh->b_reqnext;
1545                         while (bh) {
1546                                 atomic_set(&bh->b_count, 0);
1547                                 bh = bh->b_reqnext;
1548                         }
1549                         bh = tape->bh;
1550                         while (i) {
1551                                 if (bh == NULL) {
1552                                         printk(KERN_INFO "ide-tape: bug,"
1553                                                          " bh NULL\n");
1554                                         break;
1555                                 }
1556                                 min = min(i, (unsigned int)(bh->b_size -
1557                                                 atomic_read(&bh->b_count)));
1558                                 memset(bh->b_data + atomic_read(&bh->b_count),
1559                                                 0, min);
1560                                 atomic_add(min, &bh->b_count);
1561                                 i -= min;
1562                                 bh = bh->b_reqnext;
1563                         }
1564                 }
1565                 (void) idetape_add_chrdev_write_request(drive, blocks);
1566                 tape->merge_bh_size = 0;
1567         }
1568         if (tape->merge_bh != NULL) {
1569                 ide_tape_kfree_buffer(tape);
1570                 tape->merge_bh = NULL;
1571         }
1572         tape->chrdev_dir = IDETAPE_DIR_NONE;
1573 }
1574
1575 static int idetape_init_read(ide_drive_t *drive)
1576 {
1577         idetape_tape_t *tape = drive->driver_data;
1578         int bytes_read;
1579
1580         /* Initialize read operation */
1581         if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1582                 if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1583                         ide_tape_flush_merge_buffer(drive);
1584                         idetape_flush_tape_buffers(drive);
1585                 }
1586                 if (tape->merge_bh || tape->merge_bh_size) {
1587                         printk(KERN_ERR "ide-tape: merge_bh_size should be"
1588                                          " 0 now\n");
1589                         tape->merge_bh_size = 0;
1590                 }
1591                 tape->merge_bh = ide_tape_kmalloc_buffer(tape, 0, 0);
1592                 if (!tape->merge_bh)
1593                         return -ENOMEM;
1594                 tape->chrdev_dir = IDETAPE_DIR_READ;
1595
1596                 /*
1597                  * Issue a read 0 command to ensure that DSC handshake is
1598                  * switched from completion mode to buffer available mode.
1599                  * No point in issuing this if DSC overlap isn't supported, some
1600                  * drives (Seagate STT3401A) will return an error.
1601                  */
1602                 if (drive->dsc_overlap) {
1603                         bytes_read = idetape_queue_rw_tail(drive,
1604                                                         REQ_IDETAPE_READ, 0,
1605                                                         tape->merge_bh);
1606                         if (bytes_read < 0) {
1607                                 ide_tape_kfree_buffer(tape);
1608                                 tape->merge_bh = NULL;
1609                                 tape->chrdev_dir = IDETAPE_DIR_NONE;
1610                                 return bytes_read;
1611                         }
1612                 }
1613         }
1614
1615         return 0;
1616 }
1617
1618 /* called from idetape_chrdev_read() to service a chrdev read request. */
1619 static int idetape_add_chrdev_read_request(ide_drive_t *drive, int blocks)
1620 {
1621         idetape_tape_t *tape = drive->driver_data;
1622
1623         debug_log(DBG_PROCS, "Enter %s, %d blocks\n", __func__, blocks);
1624
1625         /* If we are at a filemark, return a read length of 0 */
1626         if (test_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags))
1627                 return 0;
1628
1629         idetape_init_read(drive);
1630
1631         return idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, blocks,
1632                                      tape->merge_bh);
1633 }
1634
1635 static void idetape_pad_zeros(ide_drive_t *drive, int bcount)
1636 {
1637         idetape_tape_t *tape = drive->driver_data;
1638         struct idetape_bh *bh;
1639         int blocks;
1640
1641         while (bcount) {
1642                 unsigned int count;
1643
1644                 bh = tape->merge_bh;
1645                 count = min(tape->buffer_size, bcount);
1646                 bcount -= count;
1647                 blocks = count / tape->blk_size;
1648                 while (count) {
1649                         atomic_set(&bh->b_count,
1650                                    min(count, (unsigned int)bh->b_size));
1651                         memset(bh->b_data, 0, atomic_read(&bh->b_count));
1652                         count -= atomic_read(&bh->b_count);
1653                         bh = bh->b_reqnext;
1654                 }
1655                 idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks,
1656                                       tape->merge_bh);
1657         }
1658 }
1659
1660 /*
1661  * Rewinds the tape to the Beginning Of the current Partition (BOP). We
1662  * currently support only one partition.
1663  */
1664 static int idetape_rewind_tape(ide_drive_t *drive)
1665 {
1666         int retval;
1667         struct ide_atapi_pc pc;
1668         idetape_tape_t *tape;
1669         tape = drive->driver_data;
1670
1671         debug_log(DBG_SENSE, "Enter %s\n", __func__);
1672
1673         idetape_create_rewind_cmd(drive, &pc);
1674         retval = idetape_queue_pc_tail(drive, &pc);
1675         if (retval)
1676                 return retval;
1677
1678         idetape_create_read_position_cmd(&pc);
1679         retval = idetape_queue_pc_tail(drive, &pc);
1680         if (retval)
1681                 return retval;
1682         return 0;
1683 }
1684
1685 /* mtio.h compatible commands should be issued to the chrdev interface. */
1686 static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd,
1687                                 unsigned long arg)
1688 {
1689         idetape_tape_t *tape = drive->driver_data;
1690         void __user *argp = (void __user *)arg;
1691
1692         struct idetape_config {
1693                 int dsc_rw_frequency;
1694                 int dsc_media_access_frequency;
1695                 int nr_stages;
1696         } config;
1697
1698         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1699
1700         switch (cmd) {
1701         case 0x0340:
1702                 if (copy_from_user(&config, argp, sizeof(config)))
1703                         return -EFAULT;
1704                 tape->best_dsc_rw_freq = config.dsc_rw_frequency;
1705                 break;
1706         case 0x0350:
1707                 config.dsc_rw_frequency = (int) tape->best_dsc_rw_freq;
1708                 config.nr_stages = 1;
1709                 if (copy_to_user(argp, &config, sizeof(config)))
1710                         return -EFAULT;
1711                 break;
1712         default:
1713                 return -EIO;
1714         }
1715         return 0;
1716 }
1717
1718 static int idetape_space_over_filemarks(ide_drive_t *drive, short mt_op,
1719                                         int mt_count)
1720 {
1721         idetape_tape_t *tape = drive->driver_data;
1722         struct ide_atapi_pc pc;
1723         int retval, count = 0;
1724         int sprev = !!(tape->caps[4] & 0x20);
1725
1726         if (mt_count == 0)
1727                 return 0;
1728         if (MTBSF == mt_op || MTBSFM == mt_op) {
1729                 if (!sprev)
1730                         return -EIO;
1731                 mt_count = -mt_count;
1732         }
1733
1734         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1735                 tape->merge_bh_size = 0;
1736                 if (test_and_clear_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags))
1737                         ++count;
1738                 ide_tape_discard_merge_buffer(drive, 0);
1739         }
1740
1741         switch (mt_op) {
1742         case MTFSF:
1743         case MTBSF:
1744                 idetape_create_space_cmd(&pc, mt_count - count,
1745                                          IDETAPE_SPACE_OVER_FILEMARK);
1746                 return idetape_queue_pc_tail(drive, &pc);
1747         case MTFSFM:
1748         case MTBSFM:
1749                 if (!sprev)
1750                         return -EIO;
1751                 retval = idetape_space_over_filemarks(drive, MTFSF,
1752                                                       mt_count - count);
1753                 if (retval)
1754                         return retval;
1755                 count = (MTBSFM == mt_op ? 1 : -1);
1756                 return idetape_space_over_filemarks(drive, MTFSF, count);
1757         default:
1758                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1759                                 mt_op);
1760                 return -EIO;
1761         }
1762 }
1763
1764 /*
1765  * Our character device read / write functions.
1766  *
1767  * The tape is optimized to maximize throughput when it is transferring an
1768  * integral number of the "continuous transfer limit", which is a parameter of
1769  * the specific tape (26kB on my particular tape, 32kB for Onstream).
1770  *
1771  * As of version 1.3 of the driver, the character device provides an abstract
1772  * continuous view of the media - any mix of block sizes (even 1 byte) on the
1773  * same backup/restore procedure is supported. The driver will internally
1774  * convert the requests to the recommended transfer unit, so that an unmatch
1775  * between the user's block size to the recommended size will only result in a
1776  * (slightly) increased driver overhead, but will no longer hit performance.
1777  * This is not applicable to Onstream.
1778  */
1779 static ssize_t idetape_chrdev_read(struct file *file, char __user *buf,
1780                                    size_t count, loff_t *ppos)
1781 {
1782         struct ide_tape_obj *tape = ide_tape_f(file);
1783         ide_drive_t *drive = tape->drive;
1784         ssize_t bytes_read, temp, actually_read = 0, rc;
1785         ssize_t ret = 0;
1786         u16 ctl = *(u16 *)&tape->caps[12];
1787
1788         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1789
1790         if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1791                 if (test_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags))
1792                         if (count > tape->blk_size &&
1793                             (count % tape->blk_size) == 0)
1794                                 tape->user_bs_factor = count / tape->blk_size;
1795         }
1796         rc = idetape_init_read(drive);
1797         if (rc < 0)
1798                 return rc;
1799         if (count == 0)
1800                 return (0);
1801         if (tape->merge_bh_size) {
1802                 actually_read = min((unsigned int)(tape->merge_bh_size),
1803                                     (unsigned int)count);
1804                 if (idetape_copy_stage_to_user(tape, buf, actually_read))
1805                         ret = -EFAULT;
1806                 buf += actually_read;
1807                 tape->merge_bh_size -= actually_read;
1808                 count -= actually_read;
1809         }
1810         while (count >= tape->buffer_size) {
1811                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
1812                 if (bytes_read <= 0)
1813                         goto finish;
1814                 if (idetape_copy_stage_to_user(tape, buf, bytes_read))
1815                         ret = -EFAULT;
1816                 buf += bytes_read;
1817                 count -= bytes_read;
1818                 actually_read += bytes_read;
1819         }
1820         if (count) {
1821                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
1822                 if (bytes_read <= 0)
1823                         goto finish;
1824                 temp = min((unsigned long)count, (unsigned long)bytes_read);
1825                 if (idetape_copy_stage_to_user(tape, buf, temp))
1826                         ret = -EFAULT;
1827                 actually_read += temp;
1828                 tape->merge_bh_size = bytes_read-temp;
1829         }
1830 finish:
1831         if (!actually_read && test_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags)) {
1832                 debug_log(DBG_SENSE, "%s: spacing over filemark\n", tape->name);
1833
1834                 idetape_space_over_filemarks(drive, MTFSF, 1);
1835                 return 0;
1836         }
1837
1838         return ret ? ret : actually_read;
1839 }
1840
1841 static ssize_t idetape_chrdev_write(struct file *file, const char __user *buf,
1842                                      size_t count, loff_t *ppos)
1843 {
1844         struct ide_tape_obj *tape = ide_tape_f(file);
1845         ide_drive_t *drive = tape->drive;
1846         ssize_t actually_written = 0;
1847         ssize_t ret = 0;
1848         u16 ctl = *(u16 *)&tape->caps[12];
1849
1850         /* The drive is write protected. */
1851         if (tape->write_prot)
1852                 return -EACCES;
1853
1854         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1855
1856         /* Initialize write operation */
1857         if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
1858                 if (tape->chrdev_dir == IDETAPE_DIR_READ)
1859                         ide_tape_discard_merge_buffer(drive, 1);
1860                 if (tape->merge_bh || tape->merge_bh_size) {
1861                         printk(KERN_ERR "ide-tape: merge_bh_size "
1862                                 "should be 0 now\n");
1863                         tape->merge_bh_size = 0;
1864                 }
1865                 tape->merge_bh = ide_tape_kmalloc_buffer(tape, 0, 0);
1866                 if (!tape->merge_bh)
1867                         return -ENOMEM;
1868                 tape->chrdev_dir = IDETAPE_DIR_WRITE;
1869                 idetape_init_merge_buffer(tape);
1870
1871                 /*
1872                  * Issue a write 0 command to ensure that DSC handshake is
1873                  * switched from completion mode to buffer available mode. No
1874                  * point in issuing this if DSC overlap isn't supported, some
1875                  * drives (Seagate STT3401A) will return an error.
1876                  */
1877                 if (drive->dsc_overlap) {
1878                         ssize_t retval = idetape_queue_rw_tail(drive,
1879                                                         REQ_IDETAPE_WRITE, 0,
1880                                                         tape->merge_bh);
1881                         if (retval < 0) {
1882                                 ide_tape_kfree_buffer(tape);
1883                                 tape->merge_bh = NULL;
1884                                 tape->chrdev_dir = IDETAPE_DIR_NONE;
1885                                 return retval;
1886                         }
1887                 }
1888         }
1889         if (count == 0)
1890                 return (0);
1891         if (tape->merge_bh_size) {
1892                 if (tape->merge_bh_size >= tape->buffer_size) {
1893                         printk(KERN_ERR "ide-tape: bug: merge buf too big\n");
1894                         tape->merge_bh_size = 0;
1895                 }
1896                 actually_written = min((unsigned int)
1897                                 (tape->buffer_size - tape->merge_bh_size),
1898                                 (unsigned int)count);
1899                 if (idetape_copy_stage_from_user(tape, buf, actually_written))
1900                                 ret = -EFAULT;
1901                 buf += actually_written;
1902                 tape->merge_bh_size += actually_written;
1903                 count -= actually_written;
1904
1905                 if (tape->merge_bh_size == tape->buffer_size) {
1906                         ssize_t retval;
1907                         tape->merge_bh_size = 0;
1908                         retval = idetape_add_chrdev_write_request(drive, ctl);
1909                         if (retval <= 0)
1910                                 return (retval);
1911                 }
1912         }
1913         while (count >= tape->buffer_size) {
1914                 ssize_t retval;
1915                 if (idetape_copy_stage_from_user(tape, buf, tape->buffer_size))
1916                         ret = -EFAULT;
1917                 buf += tape->buffer_size;
1918                 count -= tape->buffer_size;
1919                 retval = idetape_add_chrdev_write_request(drive, ctl);
1920                 actually_written += tape->buffer_size;
1921                 if (retval <= 0)
1922                         return (retval);
1923         }
1924         if (count) {
1925                 actually_written += count;
1926                 if (idetape_copy_stage_from_user(tape, buf, count))
1927                         ret = -EFAULT;
1928                 tape->merge_bh_size += count;
1929         }
1930         return ret ? ret : actually_written;
1931 }
1932
1933 static int idetape_write_filemark(ide_drive_t *drive)
1934 {
1935         struct ide_atapi_pc pc;
1936
1937         /* Write a filemark */
1938         idetape_create_write_filemark_cmd(drive, &pc, 1);
1939         if (idetape_queue_pc_tail(drive, &pc)) {
1940                 printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
1941                 return -EIO;
1942         }
1943         return 0;
1944 }
1945
1946 /*
1947  * Called from idetape_chrdev_ioctl when the general mtio MTIOCTOP ioctl is
1948  * requested.
1949  *
1950  * Note: MTBSF and MTBSFM are not supported when the tape doesn't support
1951  * spacing over filemarks in the reverse direction. In this case, MTFSFM is also
1952  * usually not supported.
1953  *
1954  * The following commands are currently not supported:
1955  *
1956  * MTFSS, MTBSS, MTWSM, MTSETDENSITY, MTSETDRVBUFFER, MT_ST_BOOLEANS,
1957  * MT_ST_WRITE_THRESHOLD.
1958  */
1959 static int idetape_mtioctop(ide_drive_t *drive, short mt_op, int mt_count)
1960 {
1961         idetape_tape_t *tape = drive->driver_data;
1962         struct ide_atapi_pc pc;
1963         int i, retval;
1964
1965         debug_log(DBG_ERR, "Handling MTIOCTOP ioctl: mt_op=%d, mt_count=%d\n",
1966                         mt_op, mt_count);
1967
1968         switch (mt_op) {
1969         case MTFSF:
1970         case MTFSFM:
1971         case MTBSF:
1972         case MTBSFM:
1973                 if (!mt_count)
1974                         return 0;
1975                 return idetape_space_over_filemarks(drive, mt_op, mt_count);
1976         default:
1977                 break;
1978         }
1979
1980         switch (mt_op) {
1981         case MTWEOF:
1982                 if (tape->write_prot)
1983                         return -EACCES;
1984                 ide_tape_discard_merge_buffer(drive, 1);
1985                 for (i = 0; i < mt_count; i++) {
1986                         retval = idetape_write_filemark(drive);
1987                         if (retval)
1988                                 return retval;
1989                 }
1990                 return 0;
1991         case MTREW:
1992                 ide_tape_discard_merge_buffer(drive, 0);
1993                 if (idetape_rewind_tape(drive))
1994                         return -EIO;
1995                 return 0;
1996         case MTLOAD:
1997                 ide_tape_discard_merge_buffer(drive, 0);
1998                 idetape_create_load_unload_cmd(drive, &pc,
1999                                                IDETAPE_LU_LOAD_MASK);
2000                 return idetape_queue_pc_tail(drive, &pc);
2001         case MTUNLOAD:
2002         case MTOFFL:
2003                 /*
2004                  * If door is locked, attempt to unlock before
2005                  * attempting to eject.
2006                  */
2007                 if (tape->door_locked) {
2008                         if (idetape_create_prevent_cmd(drive, &pc, 0))
2009                                 if (!idetape_queue_pc_tail(drive, &pc))
2010                                         tape->door_locked = DOOR_UNLOCKED;
2011                 }
2012                 ide_tape_discard_merge_buffer(drive, 0);
2013                 idetape_create_load_unload_cmd(drive, &pc,
2014                                               !IDETAPE_LU_LOAD_MASK);
2015                 retval = idetape_queue_pc_tail(drive, &pc);
2016                 if (!retval)
2017                         clear_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags);
2018                 return retval;
2019         case MTNOP:
2020                 ide_tape_discard_merge_buffer(drive, 0);
2021                 return idetape_flush_tape_buffers(drive);
2022         case MTRETEN:
2023                 ide_tape_discard_merge_buffer(drive, 0);
2024                 idetape_create_load_unload_cmd(drive, &pc,
2025                         IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
2026                 return idetape_queue_pc_tail(drive, &pc);
2027         case MTEOM:
2028                 idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
2029                 return idetape_queue_pc_tail(drive, &pc);
2030         case MTERASE:
2031                 (void)idetape_rewind_tape(drive);
2032                 idetape_create_erase_cmd(&pc);
2033                 return idetape_queue_pc_tail(drive, &pc);
2034         case MTSETBLK:
2035                 if (mt_count) {
2036                         if (mt_count < tape->blk_size ||
2037                             mt_count % tape->blk_size)
2038                                 return -EIO;
2039                         tape->user_bs_factor = mt_count / tape->blk_size;
2040                         clear_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags);
2041                 } else
2042                         set_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags);
2043                 return 0;
2044         case MTSEEK:
2045                 ide_tape_discard_merge_buffer(drive, 0);
2046                 return idetape_position_tape(drive,
2047                         mt_count * tape->user_bs_factor, tape->partition, 0);
2048         case MTSETPART:
2049                 ide_tape_discard_merge_buffer(drive, 0);
2050                 return idetape_position_tape(drive, 0, mt_count, 0);
2051         case MTFSR:
2052         case MTBSR:
2053         case MTLOCK:
2054                 if (!idetape_create_prevent_cmd(drive, &pc, 1))
2055                         return 0;
2056                 retval = idetape_queue_pc_tail(drive, &pc);
2057                 if (retval)
2058                         return retval;
2059                 tape->door_locked = DOOR_EXPLICITLY_LOCKED;
2060                 return 0;
2061         case MTUNLOCK:
2062                 if (!idetape_create_prevent_cmd(drive, &pc, 0))
2063                         return 0;
2064                 retval = idetape_queue_pc_tail(drive, &pc);
2065                 if (retval)
2066                         return retval;
2067                 tape->door_locked = DOOR_UNLOCKED;
2068                 return 0;
2069         default:
2070                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
2071                                 mt_op);
2072                 return -EIO;
2073         }
2074 }
2075
2076 /*
2077  * Our character device ioctls. General mtio.h magnetic io commands are
2078  * supported here, and not in the corresponding block interface. Our own
2079  * ide-tape ioctls are supported on both interfaces.
2080  */
2081 static int idetape_chrdev_ioctl(struct inode *inode, struct file *file,
2082                                 unsigned int cmd, unsigned long arg)
2083 {
2084         struct ide_tape_obj *tape = ide_tape_f(file);
2085         ide_drive_t *drive = tape->drive;
2086         struct mtop mtop;
2087         struct mtget mtget;
2088         struct mtpos mtpos;
2089         int block_offset = 0, position = tape->first_frame;
2090         void __user *argp = (void __user *)arg;
2091
2092         debug_log(DBG_CHRDEV, "Enter %s, cmd=%u\n", __func__, cmd);
2093
2094         if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
2095                 ide_tape_flush_merge_buffer(drive);
2096                 idetape_flush_tape_buffers(drive);
2097         }
2098         if (cmd == MTIOCGET || cmd == MTIOCPOS) {
2099                 block_offset = tape->merge_bh_size /
2100                         (tape->blk_size * tape->user_bs_factor);
2101                 position = idetape_read_position(drive);
2102                 if (position < 0)
2103                         return -EIO;
2104         }
2105         switch (cmd) {
2106         case MTIOCTOP:
2107                 if (copy_from_user(&mtop, argp, sizeof(struct mtop)))
2108                         return -EFAULT;
2109                 return idetape_mtioctop(drive, mtop.mt_op, mtop.mt_count);
2110         case MTIOCGET:
2111                 memset(&mtget, 0, sizeof(struct mtget));
2112                 mtget.mt_type = MT_ISSCSI2;
2113                 mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
2114                 mtget.mt_dsreg =
2115                         ((tape->blk_size * tape->user_bs_factor)
2116                          << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
2117
2118                 if (tape->drv_write_prot)
2119                         mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
2120
2121                 if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
2122                         return -EFAULT;
2123                 return 0;
2124         case MTIOCPOS:
2125                 mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
2126                 if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
2127                         return -EFAULT;
2128                 return 0;
2129         default:
2130                 if (tape->chrdev_dir == IDETAPE_DIR_READ)
2131                         ide_tape_discard_merge_buffer(drive, 1);
2132                 return idetape_blkdev_ioctl(drive, cmd, arg);
2133         }
2134 }
2135
2136 /*
2137  * Do a mode sense page 0 with block descriptor and if it succeeds set the tape
2138  * block size with the reported value.
2139  */
2140 static void ide_tape_get_bsize_from_bdesc(ide_drive_t *drive)
2141 {
2142         idetape_tape_t *tape = drive->driver_data;
2143         struct ide_atapi_pc pc;
2144
2145         idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
2146         if (idetape_queue_pc_tail(drive, &pc)) {
2147                 printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
2148                 if (tape->blk_size == 0) {
2149                         printk(KERN_WARNING "ide-tape: Cannot deal with zero "
2150                                             "block size, assuming 32k\n");
2151                         tape->blk_size = 32768;
2152                 }
2153                 return;
2154         }
2155         tape->blk_size = (pc.buf[4 + 5] << 16) +
2156                                 (pc.buf[4 + 6] << 8)  +
2157                                  pc.buf[4 + 7];
2158         tape->drv_write_prot = (pc.buf[2] & 0x80) >> 7;
2159 }
2160
2161 static int idetape_chrdev_open(struct inode *inode, struct file *filp)
2162 {
2163         unsigned int minor = iminor(inode), i = minor & ~0xc0;
2164         ide_drive_t *drive;
2165         idetape_tape_t *tape;
2166         struct ide_atapi_pc pc;
2167         int retval;
2168
2169         if (i >= MAX_HWIFS * MAX_DRIVES)
2170                 return -ENXIO;
2171
2172         lock_kernel();
2173         tape = ide_tape_chrdev_get(i);
2174         if (!tape) {
2175                 unlock_kernel();
2176                 return -ENXIO;
2177         }
2178
2179         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
2180
2181         /*
2182          * We really want to do nonseekable_open(inode, filp); here, but some
2183          * versions of tar incorrectly call lseek on tapes and bail out if that
2184          * fails.  So we disallow pread() and pwrite(), but permit lseeks.
2185          */
2186         filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
2187
2188         drive = tape->drive;
2189
2190         filp->private_data = tape;
2191
2192         if (test_and_set_bit(IDE_AFLAG_BUSY, &drive->atapi_flags)) {
2193                 retval = -EBUSY;
2194                 goto out_put_tape;
2195         }
2196
2197         retval = idetape_wait_ready(drive, 60 * HZ);
2198         if (retval) {
2199                 clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
2200                 printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
2201                 goto out_put_tape;
2202         }
2203
2204         idetape_read_position(drive);
2205         if (!test_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags))
2206                 (void)idetape_rewind_tape(drive);
2207
2208         /* Read block size and write protect status from drive. */
2209         ide_tape_get_bsize_from_bdesc(drive);
2210
2211         /* Set write protect flag if device is opened as read-only. */
2212         if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
2213                 tape->write_prot = 1;
2214         else
2215                 tape->write_prot = tape->drv_write_prot;
2216
2217         /* Make sure drive isn't write protected if user wants to write. */
2218         if (tape->write_prot) {
2219                 if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
2220                     (filp->f_flags & O_ACCMODE) == O_RDWR) {
2221                         clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
2222                         retval = -EROFS;
2223                         goto out_put_tape;
2224                 }
2225         }
2226
2227         /* Lock the tape drive door so user can't eject. */
2228         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
2229                 if (idetape_create_prevent_cmd(drive, &pc, 1)) {
2230                         if (!idetape_queue_pc_tail(drive, &pc)) {
2231                                 if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
2232                                         tape->door_locked = DOOR_LOCKED;
2233                         }
2234                 }
2235         }
2236         unlock_kernel();
2237         return 0;
2238
2239 out_put_tape:
2240         ide_tape_put(tape);
2241         unlock_kernel();
2242         return retval;
2243 }
2244
2245 static void idetape_write_release(ide_drive_t *drive, unsigned int minor)
2246 {
2247         idetape_tape_t *tape = drive->driver_data;
2248
2249         ide_tape_flush_merge_buffer(drive);
2250         tape->merge_bh = ide_tape_kmalloc_buffer(tape, 1, 0);
2251         if (tape->merge_bh != NULL) {
2252                 idetape_pad_zeros(drive, tape->blk_size *
2253                                 (tape->user_bs_factor - 1));
2254                 ide_tape_kfree_buffer(tape);
2255                 tape->merge_bh = NULL;
2256         }
2257         idetape_write_filemark(drive);
2258         idetape_flush_tape_buffers(drive);
2259         idetape_flush_tape_buffers(drive);
2260 }
2261
2262 static int idetape_chrdev_release(struct inode *inode, struct file *filp)
2263 {
2264         struct ide_tape_obj *tape = ide_tape_f(filp);
2265         ide_drive_t *drive = tape->drive;
2266         struct ide_atapi_pc pc;
2267         unsigned int minor = iminor(inode);
2268
2269         lock_kernel();
2270         tape = drive->driver_data;
2271
2272         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
2273
2274         if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
2275                 idetape_write_release(drive, minor);
2276         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
2277                 if (minor < 128)
2278                         ide_tape_discard_merge_buffer(drive, 1);
2279         }
2280
2281         if (minor < 128 && test_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags))
2282                 (void) idetape_rewind_tape(drive);
2283         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
2284                 if (tape->door_locked == DOOR_LOCKED) {
2285                         if (idetape_create_prevent_cmd(drive, &pc, 0)) {
2286                                 if (!idetape_queue_pc_tail(drive, &pc))
2287                                         tape->door_locked = DOOR_UNLOCKED;
2288                         }
2289                 }
2290         }
2291         clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
2292         ide_tape_put(tape);
2293         unlock_kernel();
2294         return 0;
2295 }
2296
2297 /*
2298  * check the contents of the ATAPI IDENTIFY command results. We return:
2299  *
2300  * 1 - If the tape can be supported by us, based on the information we have so
2301  * far.
2302  *
2303  * 0 - If this tape driver is not currently supported by us.
2304  */
2305 static int idetape_identify_device(ide_drive_t *drive)
2306 {
2307         u8 gcw[2], protocol, device_type, removable, packet_size;
2308
2309         if (drive->id_read == 0)
2310                 return 1;
2311
2312         *((unsigned short *) &gcw) = drive->id->config;
2313
2314         protocol        =   (gcw[1] & 0xC0) >> 6;
2315         device_type     =    gcw[1] & 0x1F;
2316         removable       = !!(gcw[0] & 0x80);
2317         packet_size     =    gcw[0] & 0x3;
2318
2319         /* Check that we can support this device */
2320         if (protocol != 2)
2321                 printk(KERN_ERR "ide-tape: Protocol (0x%02x) is not ATAPI\n",
2322                                 protocol);
2323         else if (device_type != 1)
2324                 printk(KERN_ERR "ide-tape: Device type (0x%02x) is not set "
2325                                 "to tape\n", device_type);
2326         else if (!removable)
2327                 printk(KERN_ERR "ide-tape: The removable flag is not set\n");
2328         else if (packet_size != 0) {
2329                 printk(KERN_ERR "ide-tape: Packet size (0x%02x) is not 12"
2330                                 " bytes\n", packet_size);
2331         } else
2332                 return 1;
2333         return 0;
2334 }
2335
2336 static void idetape_get_inquiry_results(ide_drive_t *drive)
2337 {
2338         idetape_tape_t *tape = drive->driver_data;
2339         struct ide_atapi_pc pc;
2340         char fw_rev[6], vendor_id[10], product_id[18];
2341
2342         idetape_create_inquiry_cmd(&pc);
2343         if (idetape_queue_pc_tail(drive, &pc)) {
2344                 printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
2345                                 tape->name);
2346                 return;
2347         }
2348         memcpy(vendor_id, &pc.buf[8], 8);
2349         memcpy(product_id, &pc.buf[16], 16);
2350         memcpy(fw_rev, &pc.buf[32], 4);
2351
2352         ide_fixstring(vendor_id, 10, 0);
2353         ide_fixstring(product_id, 18, 0);
2354         ide_fixstring(fw_rev, 6, 0);
2355
2356         printk(KERN_INFO "ide-tape: %s <-> %s: %s %s rev %s\n",
2357                         drive->name, tape->name, vendor_id, product_id, fw_rev);
2358 }
2359
2360 /*
2361  * Ask the tape about its various parameters. In particular, we will adjust our
2362  * data transfer buffer size to the recommended value as returned by the tape.
2363  */
2364 static void idetape_get_mode_sense_results(ide_drive_t *drive)
2365 {
2366         idetape_tape_t *tape = drive->driver_data;
2367         struct ide_atapi_pc pc;
2368         u8 *caps;
2369         u8 speed, max_speed;
2370
2371         idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
2372         if (idetape_queue_pc_tail(drive, &pc)) {
2373                 printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
2374                                 " some default values\n");
2375                 tape->blk_size = 512;
2376                 put_unaligned(52,   (u16 *)&tape->caps[12]);
2377                 put_unaligned(540,  (u16 *)&tape->caps[14]);
2378                 put_unaligned(6*52, (u16 *)&tape->caps[16]);
2379                 return;
2380         }
2381         caps = pc.buf + 4 + pc.buf[3];
2382
2383         /* convert to host order and save for later use */
2384         speed = be16_to_cpup((__be16 *)&caps[14]);
2385         max_speed = be16_to_cpup((__be16 *)&caps[8]);
2386
2387         *(u16 *)&caps[8] = max_speed;
2388         *(u16 *)&caps[12] = be16_to_cpup((__be16 *)&caps[12]);
2389         *(u16 *)&caps[14] = speed;
2390         *(u16 *)&caps[16] = be16_to_cpup((__be16 *)&caps[16]);
2391
2392         if (!speed) {
2393                 printk(KERN_INFO "ide-tape: %s: invalid tape speed "
2394                                 "(assuming 650KB/sec)\n", drive->name);
2395                 *(u16 *)&caps[14] = 650;
2396         }
2397         if (!max_speed) {
2398                 printk(KERN_INFO "ide-tape: %s: invalid max_speed "
2399                                 "(assuming 650KB/sec)\n", drive->name);
2400                 *(u16 *)&caps[8] = 650;
2401         }
2402
2403         memcpy(&tape->caps, caps, 20);
2404         if (caps[7] & 0x02)
2405                 tape->blk_size = 512;
2406         else if (caps[7] & 0x04)
2407                 tape->blk_size = 1024;
2408 }
2409
2410 #ifdef CONFIG_IDE_PROC_FS
2411 static void idetape_add_settings(ide_drive_t *drive)
2412 {
2413         idetape_tape_t *tape = drive->driver_data;
2414
2415         ide_add_setting(drive, "buffer", SETTING_READ, TYPE_SHORT, 0, 0xffff,
2416                         1, 2, (u16 *)&tape->caps[16], NULL);
2417         ide_add_setting(drive, "speed", SETTING_READ, TYPE_SHORT, 0, 0xffff,
2418                         1, 1, (u16 *)&tape->caps[14], NULL);
2419         ide_add_setting(drive, "buffer_size", SETTING_READ, TYPE_INT, 0, 0xffff,
2420                         1, 1024, &tape->buffer_size, NULL);
2421         ide_add_setting(drive, "tdsc", SETTING_RW, TYPE_INT, IDETAPE_DSC_RW_MIN,
2422                         IDETAPE_DSC_RW_MAX, 1000, HZ, &tape->best_dsc_rw_freq,
2423                         NULL);
2424         ide_add_setting(drive, "dsc_overlap", SETTING_RW, TYPE_BYTE, 0, 1, 1,
2425                         1, &drive->dsc_overlap, NULL);
2426         ide_add_setting(drive, "avg_speed", SETTING_READ, TYPE_INT, 0, 0xffff,
2427                         1, 1, &tape->avg_speed, NULL);
2428         ide_add_setting(drive, "debug_mask", SETTING_RW, TYPE_INT, 0, 0xffff, 1,
2429                         1, &tape->debug_mask, NULL);
2430 }
2431 #else
2432 static inline void idetape_add_settings(ide_drive_t *drive) { ; }
2433 #endif
2434
2435 /*
2436  * The function below is called to:
2437  *
2438  * 1. Initialize our various state variables.
2439  * 2. Ask the tape for its capabilities.
2440  * 3. Allocate a buffer which will be used for data transfer. The buffer size
2441  * is chosen based on the recommendation which we received in step 2.
2442  *
2443  * Note that at this point ide.c already assigned us an irq, so that we can
2444  * queue requests here and wait for their completion.
2445  */
2446 static void idetape_setup(ide_drive_t *drive, idetape_tape_t *tape, int minor)
2447 {
2448         unsigned long t;
2449         int speed;
2450         int buffer_size;
2451         u8 gcw[2];
2452         u16 *ctl = (u16 *)&tape->caps[12];
2453
2454         drive->pc_callback = ide_tape_callback;
2455
2456         spin_lock_init(&tape->lock);
2457         drive->dsc_overlap = 1;
2458         if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
2459                 printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
2460                                  tape->name);
2461                 drive->dsc_overlap = 0;
2462         }
2463         /* Seagate Travan drives do not support DSC overlap. */
2464         if (strstr(drive->id->model, "Seagate STT3401"))
2465                 drive->dsc_overlap = 0;
2466         tape->minor = minor;
2467         tape->name[0] = 'h';
2468         tape->name[1] = 't';
2469         tape->name[2] = '0' + minor;
2470         tape->chrdev_dir = IDETAPE_DIR_NONE;
2471         tape->pc = tape->pc_stack;
2472         *((unsigned short *) &gcw) = drive->id->config;
2473
2474         /* Command packet DRQ type */
2475         if (((gcw[0] & 0x60) >> 5) == 1)
2476                 set_bit(IDE_AFLAG_DRQ_INTERRUPT, &drive->atapi_flags);
2477
2478         idetape_get_inquiry_results(drive);
2479         idetape_get_mode_sense_results(drive);
2480         ide_tape_get_bsize_from_bdesc(drive);
2481         tape->user_bs_factor = 1;
2482         tape->buffer_size = *ctl * tape->blk_size;
2483         while (tape->buffer_size > 0xffff) {
2484                 printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
2485                 *ctl /= 2;
2486                 tape->buffer_size = *ctl * tape->blk_size;
2487         }
2488         buffer_size = tape->buffer_size;
2489         tape->pages_per_buffer = buffer_size / PAGE_SIZE;
2490         if (buffer_size % PAGE_SIZE) {
2491                 tape->pages_per_buffer++;
2492                 tape->excess_bh_size = PAGE_SIZE - buffer_size % PAGE_SIZE;
2493         }
2494
2495         /* select the "best" DSC read/write polling freq */
2496         speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
2497
2498         t = (IDETAPE_FIFO_THRESHOLD * tape->buffer_size * HZ) / (speed * 1000);
2499
2500         /*
2501          * Ensure that the number we got makes sense; limit it within
2502          * IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
2503          */
2504         tape->best_dsc_rw_freq = clamp_t(unsigned long, t, IDETAPE_DSC_RW_MIN,
2505                                          IDETAPE_DSC_RW_MAX);
2506         printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
2507                 "%lums tDSC%s\n",
2508                 drive->name, tape->name, *(u16 *)&tape->caps[14],
2509                 (*(u16 *)&tape->caps[16] * 512) / tape->buffer_size,
2510                 tape->buffer_size / 1024,
2511                 tape->best_dsc_rw_freq * 1000 / HZ,
2512                 drive->using_dma ? ", DMA":"");
2513
2514         idetape_add_settings(drive);
2515 }
2516
2517 static void ide_tape_remove(ide_drive_t *drive)
2518 {
2519         idetape_tape_t *tape = drive->driver_data;
2520
2521         ide_proc_unregister_driver(drive, tape->driver);
2522
2523         ide_unregister_region(tape->disk);
2524
2525         ide_tape_put(tape);
2526 }
2527
2528 static void ide_tape_release(struct kref *kref)
2529 {
2530         struct ide_tape_obj *tape = to_ide_tape(kref);
2531         ide_drive_t *drive = tape->drive;
2532         struct gendisk *g = tape->disk;
2533
2534         BUG_ON(tape->merge_bh_size);
2535
2536         drive->dsc_overlap = 0;
2537         drive->driver_data = NULL;
2538         device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
2539         device_destroy(idetape_sysfs_class,
2540                         MKDEV(IDETAPE_MAJOR, tape->minor + 128));
2541         idetape_devs[tape->minor] = NULL;
2542         g->private_data = NULL;
2543         put_disk(g);
2544         kfree(tape);
2545 }
2546
2547 #ifdef CONFIG_IDE_PROC_FS
2548 static int proc_idetape_read_name
2549         (char *page, char **start, off_t off, int count, int *eof, void *data)
2550 {
2551         ide_drive_t     *drive = (ide_drive_t *) data;
2552         idetape_tape_t  *tape = drive->driver_data;
2553         char            *out = page;
2554         int             len;
2555
2556         len = sprintf(out, "%s\n", tape->name);
2557         PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
2558 }
2559
2560 static ide_proc_entry_t idetape_proc[] = {
2561         { "capacity",   S_IFREG|S_IRUGO,        proc_ide_read_capacity, NULL },
2562         { "name",       S_IFREG|S_IRUGO,        proc_idetape_read_name, NULL },
2563         { NULL, 0, NULL, NULL }
2564 };
2565 #endif
2566
2567 static int ide_tape_probe(ide_drive_t *);
2568
2569 static ide_driver_t idetape_driver = {
2570         .gen_driver = {
2571                 .owner          = THIS_MODULE,
2572                 .name           = "ide-tape",
2573                 .bus            = &ide_bus_type,
2574         },
2575         .probe                  = ide_tape_probe,
2576         .remove                 = ide_tape_remove,
2577         .version                = IDETAPE_VERSION,
2578         .media                  = ide_tape,
2579         .supports_dsc_overlap   = 1,
2580         .do_request             = idetape_do_request,
2581         .end_request            = idetape_end_request,
2582         .error                  = __ide_error,
2583 #ifdef CONFIG_IDE_PROC_FS
2584         .proc                   = idetape_proc,
2585 #endif
2586 };
2587
2588 /* Our character device supporting functions, passed to register_chrdev. */
2589 static const struct file_operations idetape_fops = {
2590         .owner          = THIS_MODULE,
2591         .read           = idetape_chrdev_read,
2592         .write          = idetape_chrdev_write,
2593         .ioctl          = idetape_chrdev_ioctl,
2594         .open           = idetape_chrdev_open,
2595         .release        = idetape_chrdev_release,
2596 };
2597
2598 static int idetape_open(struct inode *inode, struct file *filp)
2599 {
2600         struct gendisk *disk = inode->i_bdev->bd_disk;
2601         struct ide_tape_obj *tape;
2602
2603         tape = ide_tape_get(disk);
2604         if (!tape)
2605                 return -ENXIO;
2606
2607         return 0;
2608 }
2609
2610 static int idetape_release(struct inode *inode, struct file *filp)
2611 {
2612         struct gendisk *disk = inode->i_bdev->bd_disk;
2613         struct ide_tape_obj *tape = ide_tape_g(disk);
2614
2615         ide_tape_put(tape);
2616
2617         return 0;
2618 }
2619
2620 static int idetape_ioctl(struct inode *inode, struct file *file,
2621                         unsigned int cmd, unsigned long arg)
2622 {
2623         struct block_device *bdev = inode->i_bdev;
2624         struct ide_tape_obj *tape = ide_tape_g(bdev->bd_disk);
2625         ide_drive_t *drive = tape->drive;
2626         int err = generic_ide_ioctl(drive, file, bdev, cmd, arg);
2627         if (err == -EINVAL)
2628                 err = idetape_blkdev_ioctl(drive, cmd, arg);
2629         return err;
2630 }
2631
2632 static struct block_device_operations idetape_block_ops = {
2633         .owner          = THIS_MODULE,
2634         .open           = idetape_open,
2635         .release        = idetape_release,
2636         .ioctl          = idetape_ioctl,
2637 };
2638
2639 static int ide_tape_probe(ide_drive_t *drive)
2640 {
2641         idetape_tape_t *tape;
2642         struct gendisk *g;
2643         int minor;
2644
2645         if (!strstr("ide-tape", drive->driver_req))
2646                 goto failed;
2647         if (!drive->present)
2648                 goto failed;
2649         if (drive->media != ide_tape)
2650                 goto failed;
2651         if (!idetape_identify_device(drive)) {
2652                 printk(KERN_ERR "ide-tape: %s: not supported by this version of"
2653                                 " the driver\n", drive->name);
2654                 goto failed;
2655         }
2656         tape = kzalloc(sizeof(idetape_tape_t), GFP_KERNEL);
2657         if (tape == NULL) {
2658                 printk(KERN_ERR "ide-tape: %s: Can't allocate a tape struct\n",
2659                                 drive->name);
2660                 goto failed;
2661         }
2662
2663         g = alloc_disk(1 << PARTN_BITS);
2664         if (!g)
2665                 goto out_free_tape;
2666
2667         ide_init_disk(g, drive);
2668
2669         ide_proc_register_driver(drive, &idetape_driver);
2670
2671         kref_init(&tape->kref);
2672
2673         tape->drive = drive;
2674         tape->driver = &idetape_driver;
2675         tape->disk = g;
2676
2677         g->private_data = &tape->driver;
2678
2679         drive->driver_data = tape;
2680
2681         mutex_lock(&idetape_ref_mutex);
2682         for (minor = 0; idetape_devs[minor]; minor++)
2683                 ;
2684         idetape_devs[minor] = tape;
2685         mutex_unlock(&idetape_ref_mutex);
2686
2687         idetape_setup(drive, tape, minor);
2688
2689         device_create_drvdata(idetape_sysfs_class, &drive->gendev,
2690                               MKDEV(IDETAPE_MAJOR, minor), NULL,
2691                               "%s", tape->name);
2692         device_create_drvdata(idetape_sysfs_class, &drive->gendev,
2693                               MKDEV(IDETAPE_MAJOR, minor + 128), NULL,
2694                               "n%s", tape->name);
2695
2696         g->fops = &idetape_block_ops;
2697         ide_register_region(g);
2698
2699         return 0;
2700
2701 out_free_tape:
2702         kfree(tape);
2703 failed:
2704         return -ENODEV;
2705 }
2706
2707 static void __exit idetape_exit(void)
2708 {
2709         driver_unregister(&idetape_driver.gen_driver);
2710         class_destroy(idetape_sysfs_class);
2711         unregister_chrdev(IDETAPE_MAJOR, "ht");
2712 }
2713
2714 static int __init idetape_init(void)
2715 {
2716         int error = 1;
2717         idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
2718         if (IS_ERR(idetape_sysfs_class)) {
2719                 idetape_sysfs_class = NULL;
2720                 printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
2721                 error = -EBUSY;
2722                 goto out;
2723         }
2724
2725         if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
2726                 printk(KERN_ERR "ide-tape: Failed to register chrdev"
2727                                 " interface\n");
2728                 error = -EBUSY;
2729                 goto out_free_class;
2730         }
2731
2732         error = driver_register(&idetape_driver.gen_driver);
2733         if (error)
2734                 goto out_free_driver;
2735
2736         return 0;
2737
2738 out_free_driver:
2739         driver_unregister(&idetape_driver.gen_driver);
2740 out_free_class:
2741         class_destroy(idetape_sysfs_class);
2742 out:
2743         return error;
2744 }
2745
2746 MODULE_ALIAS("ide:*m-tape*");
2747 module_init(idetape_init);
2748 module_exit(idetape_exit);
2749 MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
2750 MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
2751 MODULE_LICENSE("GPL");