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