Merge branches 'slab/documentation', 'slab/fixes', 'slob/cleanups' and 'slub/fixes...
[linux-2.6] / drivers / ide / ide-tape.c
1 /*
2  * IDE ATAPI streaming tape driver.
3  *
4  * Copyright (C) 1995-1999  Gadi Oxman <gadio@netvision.net.il>
5  * Copyright (C) 2003-2005  Bartlomiej Zolnierkiewicz
6  *
7  * This driver was constructed as a student project in the software laboratory
8  * of the faculty of electrical engineering in the Technion - Israel's
9  * Institute Of Technology, with the guide of Avner Lottem and Dr. Ilana David.
10  *
11  * It is hereby placed under the terms of the GNU general public license.
12  * (See linux/COPYING).
13  *
14  * For a historical changelog see
15  * Documentation/ide/ChangeLog.ide-tape.1995-2002
16  */
17
18 #define 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  * The following parameter is used to select the point in the internal tape fifo
85  * in which we will start to refill the buffer. Decreasing the following
86  * parameter will improve the system's latency and interactive response, while
87  * using a high value might improve system throughput.
88  */
89 #define IDETAPE_FIFO_THRESHOLD          2
90
91 /*
92  * DSC polling parameters.
93  *
94  * Polling for DSC (a single bit in the status register) is a very important
95  * function in ide-tape. There are two cases in which we poll for DSC:
96  *
97  * 1. Before a read/write packet command, to ensure that we can transfer data
98  * from/to the tape's data buffers, without causing an actual media access.
99  * In case the tape is not ready yet, we take out our request from the device
100  * request queue, so that ide.c could service requests from the other device
101  * on the same interface in the meantime.
102  *
103  * 2. After the successful initialization of a "media access packet command",
104  * which is a command that can take a long time to complete (the interval can
105  * range from several seconds to even an hour). Again, we postpone our request
106  * in the middle to free the bus for the other device. The polling frequency
107  * here should be lower than the read/write frequency since those media access
108  * commands are slow. We start from a "fast" frequency - IDETAPE_DSC_MA_FAST
109  * (1 second), and if we don't receive DSC after IDETAPE_DSC_MA_THRESHOLD
110  * (5 min), we switch it to a lower frequency - IDETAPE_DSC_MA_SLOW (1 min).
111  *
112  * We also set a timeout for the timer, in case something goes wrong. The
113  * timeout should be longer then the maximum execution time of a tape operation.
114  */
115
116 /* DSC timings. */
117 #define IDETAPE_DSC_RW_MIN              5*HZ/100        /* 50 msec */
118 #define IDETAPE_DSC_RW_MAX              40*HZ/100       /* 400 msec */
119 #define IDETAPE_DSC_RW_TIMEOUT          2*60*HZ         /* 2 minutes */
120 #define IDETAPE_DSC_MA_FAST             2*HZ            /* 2 seconds */
121 #define IDETAPE_DSC_MA_THRESHOLD        5*60*HZ         /* 5 minutes */
122 #define IDETAPE_DSC_MA_SLOW             30*HZ           /* 30 seconds */
123 #define IDETAPE_DSC_MA_TIMEOUT          2*60*60*HZ      /* 2 hours */
124
125 /*************************** End of tunable parameters ***********************/
126
127 /* tape directions */
128 enum {
129         IDETAPE_DIR_NONE  = (1 << 0),
130         IDETAPE_DIR_READ  = (1 << 1),
131         IDETAPE_DIR_WRITE = (1 << 2),
132 };
133
134 /* Tape door status */
135 #define DOOR_UNLOCKED                   0
136 #define DOOR_LOCKED                     1
137 #define DOOR_EXPLICITLY_LOCKED          2
138
139 /* Some defines for the SPACE command */
140 #define IDETAPE_SPACE_OVER_FILEMARK     1
141 #define IDETAPE_SPACE_TO_EOD            3
142
143 /* Some defines for the LOAD UNLOAD command */
144 #define IDETAPE_LU_LOAD_MASK            1
145 #define IDETAPE_LU_RETENSION_MASK       2
146 #define IDETAPE_LU_EOT_MASK             4
147
148 /* Structures related to the SELECT SENSE / MODE SENSE packet commands. */
149 #define IDETAPE_BLOCK_DESCRIPTOR        0
150 #define IDETAPE_CAPABILITIES_PAGE       0x2a
151
152 /*
153  * Most of our global data which we need to save even as we leave the driver due
154  * to an interrupt or a timer event is stored in the struct defined below.
155  */
156 typedef struct ide_tape_obj {
157         ide_drive_t             *drive;
158         struct ide_driver       *driver;
159         struct gendisk          *disk;
160         struct device           dev;
161
162         /* used by REQ_IDETAPE_{READ,WRITE} requests */
163         struct ide_atapi_pc queued_pc;
164
165         /*
166          * DSC polling variables.
167          *
168          * While polling for DSC we use postponed_rq to postpone the current
169          * request so that ide.c will be able to service pending requests on the
170          * other device. Note that at most we will have only one DSC (usually
171          * data transfer) request in the device request queue.
172          */
173         struct request *postponed_rq;
174         /* The time in which we started polling for DSC */
175         unsigned long dsc_polling_start;
176         /* Timer used to poll for dsc */
177         struct timer_list dsc_timer;
178         /* Read/Write dsc polling frequency */
179         unsigned long best_dsc_rw_freq;
180         unsigned long dsc_poll_freq;
181         unsigned long dsc_timeout;
182
183         /* Read position information */
184         u8 partition;
185         /* Current block */
186         unsigned int first_frame;
187
188         /* Last error information */
189         u8 sense_key, asc, ascq;
190
191         /* Character device operation */
192         unsigned int minor;
193         /* device name */
194         char name[4];
195         /* Current character device data transfer direction */
196         u8 chrdev_dir;
197
198         /* tape block size, usually 512 or 1024 bytes */
199         unsigned short blk_size;
200         int user_bs_factor;
201
202         /* Copy of the tape's Capabilities and Mechanical Page */
203         u8 caps[20];
204
205         /*
206          * Active data transfer request parameters.
207          *
208          * At most, there is only one ide-tape originated data transfer request
209          * in the device request queue. This allows ide.c to easily service
210          * requests from the other device when we postpone our active request.
211          */
212
213         /* Data buffer size chosen based on the tape's recommendation */
214         int buffer_size;
215         /* Staging buffer of buffer_size bytes */
216         void *buf;
217         /* The read/write cursor */
218         void *cur;
219         /* The number of valid bytes in buf */
220         size_t valid;
221
222         /* Measures average tape speed */
223         unsigned long avg_time;
224         int avg_size;
225         int avg_speed;
226
227         /* the door is currently locked */
228         int door_locked;
229         /* the tape hardware is write protected */
230         char drv_write_prot;
231         /* the tape is write protected (hardware or opened as read-only) */
232         char write_prot;
233
234         u32 debug_mask;
235 } idetape_tape_t;
236
237 static DEFINE_MUTEX(idetape_ref_mutex);
238
239 static struct class *idetape_sysfs_class;
240
241 static void ide_tape_release(struct device *);
242
243 static struct ide_tape_obj *idetape_devs[MAX_HWIFS * MAX_DRIVES];
244
245 static struct ide_tape_obj *ide_tape_get(struct gendisk *disk, bool cdev,
246                                          unsigned int i)
247 {
248         struct ide_tape_obj *tape = NULL;
249
250         mutex_lock(&idetape_ref_mutex);
251
252         if (cdev)
253                 tape = idetape_devs[i];
254         else
255                 tape = ide_drv_g(disk, ide_tape_obj);
256
257         if (tape) {
258                 if (ide_device_get(tape->drive))
259                         tape = NULL;
260                 else
261                         get_device(&tape->dev);
262         }
263
264         mutex_unlock(&idetape_ref_mutex);
265         return tape;
266 }
267
268 static void ide_tape_put(struct ide_tape_obj *tape)
269 {
270         ide_drive_t *drive = tape->drive;
271
272         mutex_lock(&idetape_ref_mutex);
273         put_device(&tape->dev);
274         ide_device_put(drive);
275         mutex_unlock(&idetape_ref_mutex);
276 }
277
278 /*
279  * called on each failed packet command retry to analyze the request sense. We
280  * currently do not utilize this information.
281  */
282 static void idetape_analyze_error(ide_drive_t *drive, u8 *sense)
283 {
284         idetape_tape_t *tape = drive->driver_data;
285         struct ide_atapi_pc *pc = drive->failed_pc;
286
287         tape->sense_key = sense[2] & 0xF;
288         tape->asc       = sense[12];
289         tape->ascq      = sense[13];
290
291         debug_log(DBG_ERR, "pc = %x, sense key = %x, asc = %x, ascq = %x\n",
292                  pc->c[0], tape->sense_key, tape->asc, tape->ascq);
293
294         /* Correct pc->xferred by asking the tape.       */
295         if (pc->flags & PC_FLAG_DMA_ERROR)
296                 pc->xferred = pc->req_xfer -
297                         tape->blk_size *
298                         get_unaligned_be32(&sense[3]);
299
300         /*
301          * If error was the result of a zero-length read or write command,
302          * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
303          * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
304          */
305         if ((pc->c[0] == READ_6 || pc->c[0] == WRITE_6)
306             /* length == 0 */
307             && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
308                 if (tape->sense_key == 5) {
309                         /* don't report an error, everything's ok */
310                         pc->error = 0;
311                         /* don't retry read/write */
312                         pc->flags |= PC_FLAG_ABORT;
313                 }
314         }
315         if (pc->c[0] == READ_6 && (sense[2] & 0x80)) {
316                 pc->error = IDE_DRV_ERROR_FILEMARK;
317                 pc->flags |= PC_FLAG_ABORT;
318         }
319         if (pc->c[0] == WRITE_6) {
320                 if ((sense[2] & 0x40) || (tape->sense_key == 0xd
321                      && tape->asc == 0x0 && tape->ascq == 0x2)) {
322                         pc->error = IDE_DRV_ERROR_EOD;
323                         pc->flags |= PC_FLAG_ABORT;
324                 }
325         }
326         if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
327                 if (tape->sense_key == 8) {
328                         pc->error = IDE_DRV_ERROR_EOD;
329                         pc->flags |= PC_FLAG_ABORT;
330                 }
331                 if (!(pc->flags & PC_FLAG_ABORT) &&
332                     pc->xferred)
333                         pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
334         }
335 }
336
337 static void ide_tape_handle_dsc(ide_drive_t *);
338
339 static int ide_tape_callback(ide_drive_t *drive, int dsc)
340 {
341         idetape_tape_t *tape = drive->driver_data;
342         struct ide_atapi_pc *pc = drive->pc;
343         struct request *rq = drive->hwif->rq;
344         int uptodate = pc->error ? 0 : 1;
345         int err = uptodate ? 0 : IDE_DRV_ERROR_GENERAL;
346
347         debug_log(DBG_PROCS, "Enter %s\n", __func__);
348
349         if (dsc)
350                 ide_tape_handle_dsc(drive);
351
352         if (drive->failed_pc == pc)
353                 drive->failed_pc = NULL;
354
355         if (pc->c[0] == REQUEST_SENSE) {
356                 if (uptodate)
357                         idetape_analyze_error(drive, pc->buf);
358                 else
359                         printk(KERN_ERR "ide-tape: Error in REQUEST SENSE "
360                                         "itself - Aborting request!\n");
361         } else if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
362                 int blocks = pc->xferred / tape->blk_size;
363
364                 tape->avg_size += blocks * tape->blk_size;
365
366                 if (time_after_eq(jiffies, tape->avg_time + HZ)) {
367                         tape->avg_speed = tape->avg_size * HZ /
368                                 (jiffies - tape->avg_time) / 1024;
369                         tape->avg_size = 0;
370                         tape->avg_time = jiffies;
371                 }
372
373                 tape->first_frame += blocks;
374                 rq->resid_len -= blocks * tape->blk_size;
375
376                 if (pc->error) {
377                         uptodate = 0;
378                         err = pc->error;
379                 }
380         } else if (pc->c[0] == READ_POSITION && uptodate) {
381                 u8 *readpos = pc->buf;
382
383                 debug_log(DBG_SENSE, "BOP - %s\n",
384                                 (readpos[0] & 0x80) ? "Yes" : "No");
385                 debug_log(DBG_SENSE, "EOP - %s\n",
386                                 (readpos[0] & 0x40) ? "Yes" : "No");
387
388                 if (readpos[0] & 0x4) {
389                         printk(KERN_INFO "ide-tape: Block location is unknown"
390                                          "to the tape\n");
391                         clear_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
392                                   &drive->atapi_flags);
393                         uptodate = 0;
394                         err = IDE_DRV_ERROR_GENERAL;
395                 } else {
396                         debug_log(DBG_SENSE, "Block Location - %u\n",
397                                         be32_to_cpup((__be32 *)&readpos[4]));
398
399                         tape->partition = readpos[1];
400                         tape->first_frame = be32_to_cpup((__be32 *)&readpos[4]);
401                         set_bit(ilog2(IDE_AFLAG_ADDRESS_VALID),
402                                 &drive->atapi_flags);
403                 }
404         }
405
406         rq->errors = err;
407
408         return uptodate;
409 }
410
411 /*
412  * Postpone the current request so that ide.c will be able to service requests
413  * from another device on the same port while we are polling for DSC.
414  */
415 static void idetape_postpone_request(ide_drive_t *drive)
416 {
417         idetape_tape_t *tape = drive->driver_data;
418
419         debug_log(DBG_PROCS, "Enter %s\n", __func__);
420
421         tape->postponed_rq = drive->hwif->rq;
422
423         ide_stall_queue(drive, tape->dsc_poll_freq);
424 }
425
426 static void ide_tape_handle_dsc(ide_drive_t *drive)
427 {
428         idetape_tape_t *tape = drive->driver_data;
429
430         /* Media access command */
431         tape->dsc_polling_start = jiffies;
432         tape->dsc_poll_freq = IDETAPE_DSC_MA_FAST;
433         tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
434         /* Allow ide.c to handle other requests */
435         idetape_postpone_request(drive);
436 }
437
438 /*
439  * Packet Command Interface
440  *
441  * The current Packet Command is available in drive->pc, and will not change
442  * until we finish handling it. Each packet command is associated with a
443  * callback function that will be called when the command is finished.
444  *
445  * The handling will be done in three stages:
446  *
447  * 1. ide_tape_issue_pc will send the packet command to the drive, and will set
448  * the interrupt handler to ide_pc_intr.
449  *
450  * 2. On each interrupt, ide_pc_intr will be called. This step will be
451  * repeated until the device signals us that no more interrupts will be issued.
452  *
453  * 3. ATAPI Tape media access commands have immediate status with a delayed
454  * process. In case of a successful initiation of a media access packet command,
455  * the DSC bit will be set when the actual execution of the command is finished.
456  * Since the tape drive will not issue an interrupt, we have to poll for this
457  * event. In this case, we define the request as "low priority request" by
458  * setting rq_status to IDETAPE_RQ_POSTPONED, set a timer to poll for DSC and
459  * exit the driver.
460  *
461  * ide.c will then give higher priority to requests which originate from the
462  * other device, until will change rq_status to RQ_ACTIVE.
463  *
464  * 4. When the packet command is finished, it will be checked for errors.
465  *
466  * 5. In case an error was found, we queue a request sense packet command in
467  * front of the request queue and retry the operation up to
468  * IDETAPE_MAX_PC_RETRIES times.
469  *
470  * 6. In case no error was found, or we decided to give up and not to retry
471  * again, the callback function will be called and then we will handle the next
472  * request.
473  */
474
475 static ide_startstop_t ide_tape_issue_pc(ide_drive_t *drive,
476                                          struct ide_cmd *cmd,
477                                          struct ide_atapi_pc *pc)
478 {
479         idetape_tape_t *tape = drive->driver_data;
480
481         if (drive->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
482                 drive->failed_pc = pc;
483
484         /* Set the current packet command */
485         drive->pc = pc;
486
487         if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
488                 (pc->flags & PC_FLAG_ABORT)) {
489                 unsigned int done = blk_rq_bytes(drive->hwif->rq);
490
491                 /*
492                  * We will "abort" retrying a packet command in case legitimate
493                  * error code was received (crossing a filemark, or end of the
494                  * media, for example).
495                  */
496                 if (!(pc->flags & PC_FLAG_ABORT)) {
497                         if (!(pc->c[0] == TEST_UNIT_READY &&
498                               tape->sense_key == 2 && tape->asc == 4 &&
499                              (tape->ascq == 1 || tape->ascq == 8))) {
500                                 printk(KERN_ERR "ide-tape: %s: I/O error, "
501                                                 "pc = %2x, key = %2x, "
502                                                 "asc = %2x, ascq = %2x\n",
503                                                 tape->name, pc->c[0],
504                                                 tape->sense_key, tape->asc,
505                                                 tape->ascq);
506                         }
507                         /* Giving up */
508                         pc->error = IDE_DRV_ERROR_GENERAL;
509                 }
510
511                 drive->failed_pc = NULL;
512                 drive->pc_callback(drive, 0);
513                 ide_complete_rq(drive, -EIO, done);
514                 return ide_stopped;
515         }
516         debug_log(DBG_SENSE, "Retry #%d, cmd = %02X\n", pc->retries, pc->c[0]);
517
518         pc->retries++;
519
520         return ide_issue_pc(drive, cmd);
521 }
522
523 /* A mode sense command is used to "sense" tape parameters. */
524 static void idetape_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
525 {
526         ide_init_pc(pc);
527         pc->c[0] = MODE_SENSE;
528         if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
529                 /* DBD = 1 - Don't return block descriptors */
530                 pc->c[1] = 8;
531         pc->c[2] = page_code;
532         /*
533          * Changed pc->c[3] to 0 (255 will at best return unused info).
534          *
535          * For SCSI this byte is defined as subpage instead of high byte
536          * of length and some IDE drives seem to interpret it this way
537          * and return an error when 255 is used.
538          */
539         pc->c[3] = 0;
540         /* We will just discard data in that case */
541         pc->c[4] = 255;
542         if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
543                 pc->req_xfer = 12;
544         else if (page_code == IDETAPE_CAPABILITIES_PAGE)
545                 pc->req_xfer = 24;
546         else
547                 pc->req_xfer = 50;
548 }
549
550 static ide_startstop_t idetape_media_access_finished(ide_drive_t *drive)
551 {
552         ide_hwif_t *hwif = drive->hwif;
553         idetape_tape_t *tape = drive->driver_data;
554         struct ide_atapi_pc *pc = drive->pc;
555         u8 stat;
556
557         stat = hwif->tp_ops->read_status(hwif);
558
559         if (stat & ATA_DSC) {
560                 if (stat & ATA_ERR) {
561                         /* Error detected */
562                         if (pc->c[0] != TEST_UNIT_READY)
563                                 printk(KERN_ERR "ide-tape: %s: I/O error, ",
564                                                 tape->name);
565                         /* Retry operation */
566                         ide_retry_pc(drive);
567                         return ide_stopped;
568                 }
569                 pc->error = 0;
570         } else {
571                 pc->error = IDE_DRV_ERROR_GENERAL;
572                 drive->failed_pc = NULL;
573         }
574         drive->pc_callback(drive, 0);
575         return ide_stopped;
576 }
577
578 static void ide_tape_create_rw_cmd(idetape_tape_t *tape,
579                                    struct ide_atapi_pc *pc, struct request *rq,
580                                    u8 opcode)
581 {
582         unsigned int length = blk_rq_sectors(rq);
583
584         ide_init_pc(pc);
585         put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
586         pc->c[1] = 1;
587         pc->buf = NULL;
588         pc->buf_size = length * tape->blk_size;
589         pc->req_xfer = pc->buf_size;
590         if (pc->req_xfer == tape->buffer_size)
591                 pc->flags |= PC_FLAG_DMA_OK;
592
593         if (opcode == READ_6)
594                 pc->c[0] = READ_6;
595         else if (opcode == WRITE_6) {
596                 pc->c[0] = WRITE_6;
597                 pc->flags |= PC_FLAG_WRITING;
598         }
599
600         memcpy(rq->cmd, pc->c, 12);
601 }
602
603 static ide_startstop_t idetape_do_request(ide_drive_t *drive,
604                                           struct request *rq, sector_t block)
605 {
606         ide_hwif_t *hwif = drive->hwif;
607         idetape_tape_t *tape = drive->driver_data;
608         struct ide_atapi_pc *pc = NULL;
609         struct request *postponed_rq = tape->postponed_rq;
610         struct ide_cmd cmd;
611         u8 stat;
612
613         debug_log(DBG_SENSE, "sector: %llu, nr_sectors: %u\n"
614                   (unsigned long long)blk_rq_pos(rq), blk_rq_sectors(rq));
615
616         if (!(blk_special_request(rq) || blk_sense_request(rq))) {
617                 /* We do not support buffer cache originated requests. */
618                 printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
619                         "request queue (%d)\n", drive->name, rq->cmd_type);
620                 if (blk_fs_request(rq) == 0 && rq->errors == 0)
621                         rq->errors = -EIO;
622                 ide_complete_rq(drive, -EIO, ide_rq_bytes(rq));
623                 return ide_stopped;
624         }
625
626         /* Retry a failed packet command */
627         if (drive->failed_pc && drive->pc->c[0] == REQUEST_SENSE) {
628                 pc = drive->failed_pc;
629                 goto out;
630         }
631
632         if (postponed_rq != NULL)
633                 if (rq != postponed_rq) {
634                         printk(KERN_ERR "ide-tape: ide-tape.c bug - "
635                                         "Two DSC requests were queued\n");
636                         drive->failed_pc = NULL;
637                         rq->errors = 0;
638                         ide_complete_rq(drive, 0, blk_rq_bytes(rq));
639                         return ide_stopped;
640                 }
641
642         tape->postponed_rq = NULL;
643
644         /*
645          * If the tape is still busy, postpone our request and service
646          * the other device meanwhile.
647          */
648         stat = hwif->tp_ops->read_status(hwif);
649
650         if ((drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) == 0 &&
651             (rq->cmd[13] & REQ_IDETAPE_PC2) == 0)
652                 drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
653
654         if (drive->dev_flags & IDE_DFLAG_POST_RESET) {
655                 drive->atapi_flags |= IDE_AFLAG_IGNORE_DSC;
656                 drive->dev_flags &= ~IDE_DFLAG_POST_RESET;
657         }
658
659         if (!(drive->atapi_flags & IDE_AFLAG_IGNORE_DSC) &&
660             !(stat & ATA_DSC)) {
661                 if (postponed_rq == NULL) {
662                         tape->dsc_polling_start = jiffies;
663                         tape->dsc_poll_freq = tape->best_dsc_rw_freq;
664                         tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
665                 } else if (time_after(jiffies, tape->dsc_timeout)) {
666                         printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
667                                 tape->name);
668                         if (rq->cmd[13] & REQ_IDETAPE_PC2) {
669                                 idetape_media_access_finished(drive);
670                                 return ide_stopped;
671                         } else {
672                                 return ide_do_reset(drive);
673                         }
674                 } else if (time_after(jiffies,
675                                         tape->dsc_polling_start +
676                                         IDETAPE_DSC_MA_THRESHOLD))
677                         tape->dsc_poll_freq = IDETAPE_DSC_MA_SLOW;
678                 idetape_postpone_request(drive);
679                 return ide_stopped;
680         } else
681                 drive->atapi_flags &= ~IDE_AFLAG_IGNORE_DSC;
682
683         if (rq->cmd[13] & REQ_IDETAPE_READ) {
684                 pc = &tape->queued_pc;
685                 ide_tape_create_rw_cmd(tape, pc, rq, READ_6);
686                 goto out;
687         }
688         if (rq->cmd[13] & REQ_IDETAPE_WRITE) {
689                 pc = &tape->queued_pc;
690                 ide_tape_create_rw_cmd(tape, pc, rq, WRITE_6);
691                 goto out;
692         }
693         if (rq->cmd[13] & REQ_IDETAPE_PC1) {
694                 pc = (struct ide_atapi_pc *)rq->special;
695                 rq->cmd[13] &= ~(REQ_IDETAPE_PC1);
696                 rq->cmd[13] |= REQ_IDETAPE_PC2;
697                 goto out;
698         }
699         if (rq->cmd[13] & REQ_IDETAPE_PC2) {
700                 idetape_media_access_finished(drive);
701                 return ide_stopped;
702         }
703         BUG();
704
705 out:
706         /* prepare sense request for this command */
707         ide_prep_sense(drive, rq);
708
709         memset(&cmd, 0, sizeof(cmd));
710
711         if (rq_data_dir(rq))
712                 cmd.tf_flags |= IDE_TFLAG_WRITE;
713
714         cmd.rq = rq;
715
716         ide_init_sg_cmd(&cmd, pc->req_xfer);
717         ide_map_sg(drive, &cmd);
718
719         return ide_tape_issue_pc(drive, &cmd, pc);
720 }
721
722 /*
723  * Write a filemark if write_filemark=1. Flush the device buffers without
724  * writing a filemark otherwise.
725  */
726 static void idetape_create_write_filemark_cmd(ide_drive_t *drive,
727                 struct ide_atapi_pc *pc, int write_filemark)
728 {
729         ide_init_pc(pc);
730         pc->c[0] = WRITE_FILEMARKS;
731         pc->c[4] = write_filemark;
732         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
733 }
734
735 static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
736 {
737         idetape_tape_t *tape = drive->driver_data;
738         struct gendisk *disk = tape->disk;
739         int load_attempted = 0;
740
741         /* Wait for the tape to become ready */
742         set_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT), &drive->atapi_flags);
743         timeout += jiffies;
744         while (time_before(jiffies, timeout)) {
745                 if (ide_do_test_unit_ready(drive, disk) == 0)
746                         return 0;
747                 if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
748                     || (tape->asc == 0x3A)) {
749                         /* no media */
750                         if (load_attempted)
751                                 return -ENOMEDIUM;
752                         ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
753                         load_attempted = 1;
754                 /* not about to be ready */
755                 } else if (!(tape->sense_key == 2 && tape->asc == 4 &&
756                              (tape->ascq == 1 || tape->ascq == 8)))
757                         return -EIO;
758                 msleep(100);
759         }
760         return -EIO;
761 }
762
763 static int idetape_flush_tape_buffers(ide_drive_t *drive)
764 {
765         struct ide_tape_obj *tape = drive->driver_data;
766         struct ide_atapi_pc pc;
767         int rc;
768
769         idetape_create_write_filemark_cmd(drive, &pc, 0);
770         rc = ide_queue_pc_tail(drive, tape->disk, &pc);
771         if (rc)
772                 return rc;
773         idetape_wait_ready(drive, 60 * 5 * HZ);
774         return 0;
775 }
776
777 static void idetape_create_read_position_cmd(struct ide_atapi_pc *pc)
778 {
779         ide_init_pc(pc);
780         pc->c[0] = READ_POSITION;
781         pc->req_xfer = 20;
782 }
783
784 static int idetape_read_position(ide_drive_t *drive)
785 {
786         idetape_tape_t *tape = drive->driver_data;
787         struct ide_atapi_pc pc;
788         int position;
789
790         debug_log(DBG_PROCS, "Enter %s\n", __func__);
791
792         idetape_create_read_position_cmd(&pc);
793         if (ide_queue_pc_tail(drive, tape->disk, &pc))
794                 return -1;
795         position = tape->first_frame;
796         return position;
797 }
798
799 static void idetape_create_locate_cmd(ide_drive_t *drive,
800                 struct ide_atapi_pc *pc,
801                 unsigned int block, u8 partition, int skip)
802 {
803         ide_init_pc(pc);
804         pc->c[0] = POSITION_TO_ELEMENT;
805         pc->c[1] = 2;
806         put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[3]);
807         pc->c[8] = partition;
808         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
809 }
810
811 static void __ide_tape_discard_merge_buffer(ide_drive_t *drive)
812 {
813         idetape_tape_t *tape = drive->driver_data;
814
815         if (tape->chrdev_dir != IDETAPE_DIR_READ)
816                 return;
817
818         clear_bit(ilog2(IDE_AFLAG_FILEMARK), &drive->atapi_flags);
819         tape->valid = 0;
820         if (tape->buf != NULL) {
821                 kfree(tape->buf);
822                 tape->buf = NULL;
823         }
824
825         tape->chrdev_dir = IDETAPE_DIR_NONE;
826 }
827
828 /*
829  * Position the tape to the requested block using the LOCATE packet command.
830  * A READ POSITION command is then issued to check where we are positioned. Like
831  * all higher level operations, we queue the commands at the tail of the request
832  * queue and wait for their completion.
833  */
834 static int idetape_position_tape(ide_drive_t *drive, unsigned int block,
835                 u8 partition, int skip)
836 {
837         idetape_tape_t *tape = drive->driver_data;
838         struct gendisk *disk = tape->disk;
839         int retval;
840         struct ide_atapi_pc pc;
841
842         if (tape->chrdev_dir == IDETAPE_DIR_READ)
843                 __ide_tape_discard_merge_buffer(drive);
844         idetape_wait_ready(drive, 60 * 5 * HZ);
845         idetape_create_locate_cmd(drive, &pc, block, partition, skip);
846         retval = ide_queue_pc_tail(drive, disk, &pc);
847         if (retval)
848                 return (retval);
849
850         idetape_create_read_position_cmd(&pc);
851         return ide_queue_pc_tail(drive, disk, &pc);
852 }
853
854 static void ide_tape_discard_merge_buffer(ide_drive_t *drive,
855                                           int restore_position)
856 {
857         idetape_tape_t *tape = drive->driver_data;
858         int seek, position;
859
860         __ide_tape_discard_merge_buffer(drive);
861         if (restore_position) {
862                 position = idetape_read_position(drive);
863                 seek = position > 0 ? position : 0;
864                 if (idetape_position_tape(drive, seek, 0, 0)) {
865                         printk(KERN_INFO "ide-tape: %s: position_tape failed in"
866                                          " %s\n", tape->name, __func__);
867                         return;
868                 }
869         }
870 }
871
872 /*
873  * Generate a read/write request for the block device interface and wait for it
874  * to be serviced.
875  */
876 static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int size)
877 {
878         idetape_tape_t *tape = drive->driver_data;
879         struct request *rq;
880         int ret;
881
882         debug_log(DBG_SENSE, "%s: cmd=%d\n", __func__, cmd);
883         BUG_ON(cmd != REQ_IDETAPE_READ && cmd != REQ_IDETAPE_WRITE);
884         BUG_ON(size < 0 || size % tape->blk_size);
885
886         rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
887         rq->cmd_type = REQ_TYPE_SPECIAL;
888         rq->cmd[13] = cmd;
889         rq->rq_disk = tape->disk;
890         rq->__sector = tape->first_frame;
891
892         if (size) {
893                 ret = blk_rq_map_kern(drive->queue, rq, tape->buf, size,
894                                       __GFP_WAIT);
895                 if (ret)
896                         goto out_put;
897         }
898
899         blk_execute_rq(drive->queue, tape->disk, rq, 0);
900
901         /* calculate the number of transferred bytes and update buffer state */
902         size -= rq->resid_len;
903         tape->cur = tape->buf;
904         if (cmd == REQ_IDETAPE_READ)
905                 tape->valid = size;
906         else
907                 tape->valid = 0;
908
909         ret = size;
910         if (rq->errors == IDE_DRV_ERROR_GENERAL)
911                 ret = -EIO;
912 out_put:
913         blk_put_request(rq);
914         return ret;
915 }
916
917 static void idetape_create_inquiry_cmd(struct ide_atapi_pc *pc)
918 {
919         ide_init_pc(pc);
920         pc->c[0] = INQUIRY;
921         pc->c[4] = 254;
922         pc->req_xfer = 254;
923 }
924
925 static void idetape_create_rewind_cmd(ide_drive_t *drive,
926                 struct ide_atapi_pc *pc)
927 {
928         ide_init_pc(pc);
929         pc->c[0] = REZERO_UNIT;
930         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
931 }
932
933 static void idetape_create_erase_cmd(struct ide_atapi_pc *pc)
934 {
935         ide_init_pc(pc);
936         pc->c[0] = ERASE;
937         pc->c[1] = 1;
938         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
939 }
940
941 static void idetape_create_space_cmd(struct ide_atapi_pc *pc, int count, u8 cmd)
942 {
943         ide_init_pc(pc);
944         pc->c[0] = SPACE;
945         put_unaligned(cpu_to_be32(count), (unsigned int *) &pc->c[1]);
946         pc->c[1] = cmd;
947         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
948 }
949
950 static void ide_tape_flush_merge_buffer(ide_drive_t *drive)
951 {
952         idetape_tape_t *tape = drive->driver_data;
953
954         if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
955                 printk(KERN_ERR "ide-tape: bug: Trying to empty merge buffer"
956                                 " but we are not writing.\n");
957                 return;
958         }
959         if (tape->buf) {
960                 size_t aligned = roundup(tape->valid, tape->blk_size);
961
962                 memset(tape->cur, 0, aligned - tape->valid);
963                 idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, aligned);
964                 kfree(tape->buf);
965                 tape->buf = NULL;
966         }
967         tape->chrdev_dir = IDETAPE_DIR_NONE;
968 }
969
970 static int idetape_init_rw(ide_drive_t *drive, int dir)
971 {
972         idetape_tape_t *tape = drive->driver_data;
973         int rc;
974
975         BUG_ON(dir != IDETAPE_DIR_READ && dir != IDETAPE_DIR_WRITE);
976
977         if (tape->chrdev_dir == dir)
978                 return 0;
979
980         if (tape->chrdev_dir == IDETAPE_DIR_READ)
981                 ide_tape_discard_merge_buffer(drive, 1);
982         else if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
983                 ide_tape_flush_merge_buffer(drive);
984                 idetape_flush_tape_buffers(drive);
985         }
986
987         if (tape->buf || tape->valid) {
988                 printk(KERN_ERR "ide-tape: valid should be 0 now\n");
989                 tape->valid = 0;
990         }
991
992         tape->buf = kmalloc(tape->buffer_size, GFP_KERNEL);
993         if (!tape->buf)
994                 return -ENOMEM;
995         tape->chrdev_dir = dir;
996         tape->cur = tape->buf;
997
998         /*
999          * Issue a 0 rw command to ensure that DSC handshake is
1000          * switched from completion mode to buffer available mode.  No
1001          * point in issuing this if DSC overlap isn't supported, some
1002          * drives (Seagate STT3401A) will return an error.
1003          */
1004         if (drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) {
1005                 int cmd = dir == IDETAPE_DIR_READ ? REQ_IDETAPE_READ
1006                                                   : REQ_IDETAPE_WRITE;
1007
1008                 rc = idetape_queue_rw_tail(drive, cmd, 0);
1009                 if (rc < 0) {
1010                         kfree(tape->buf);
1011                         tape->buf = NULL;
1012                         tape->chrdev_dir = IDETAPE_DIR_NONE;
1013                         return rc;
1014                 }
1015         }
1016
1017         return 0;
1018 }
1019
1020 static void idetape_pad_zeros(ide_drive_t *drive, int bcount)
1021 {
1022         idetape_tape_t *tape = drive->driver_data;
1023
1024         memset(tape->buf, 0, tape->buffer_size);
1025
1026         while (bcount) {
1027                 unsigned int count = min(tape->buffer_size, bcount);
1028
1029                 idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, count);
1030                 bcount -= count;
1031         }
1032 }
1033
1034 /*
1035  * Rewinds the tape to the Beginning Of the current Partition (BOP). We
1036  * currently support only one partition.
1037  */
1038 static int idetape_rewind_tape(ide_drive_t *drive)
1039 {
1040         struct ide_tape_obj *tape = drive->driver_data;
1041         struct gendisk *disk = tape->disk;
1042         int retval;
1043         struct ide_atapi_pc pc;
1044
1045         debug_log(DBG_SENSE, "Enter %s\n", __func__);
1046
1047         idetape_create_rewind_cmd(drive, &pc);
1048         retval = ide_queue_pc_tail(drive, disk, &pc);
1049         if (retval)
1050                 return retval;
1051
1052         idetape_create_read_position_cmd(&pc);
1053         retval = ide_queue_pc_tail(drive, disk, &pc);
1054         if (retval)
1055                 return retval;
1056         return 0;
1057 }
1058
1059 /* mtio.h compatible commands should be issued to the chrdev interface. */
1060 static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd,
1061                                 unsigned long arg)
1062 {
1063         idetape_tape_t *tape = drive->driver_data;
1064         void __user *argp = (void __user *)arg;
1065
1066         struct idetape_config {
1067                 int dsc_rw_frequency;
1068                 int dsc_media_access_frequency;
1069                 int nr_stages;
1070         } config;
1071
1072         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1073
1074         switch (cmd) {
1075         case 0x0340:
1076                 if (copy_from_user(&config, argp, sizeof(config)))
1077                         return -EFAULT;
1078                 tape->best_dsc_rw_freq = config.dsc_rw_frequency;
1079                 break;
1080         case 0x0350:
1081                 config.dsc_rw_frequency = (int) tape->best_dsc_rw_freq;
1082                 config.nr_stages = 1;
1083                 if (copy_to_user(argp, &config, sizeof(config)))
1084                         return -EFAULT;
1085                 break;
1086         default:
1087                 return -EIO;
1088         }
1089         return 0;
1090 }
1091
1092 static int idetape_space_over_filemarks(ide_drive_t *drive, short mt_op,
1093                                         int mt_count)
1094 {
1095         idetape_tape_t *tape = drive->driver_data;
1096         struct gendisk *disk = tape->disk;
1097         struct ide_atapi_pc pc;
1098         int retval, count = 0;
1099         int sprev = !!(tape->caps[4] & 0x20);
1100
1101         if (mt_count == 0)
1102                 return 0;
1103         if (MTBSF == mt_op || MTBSFM == mt_op) {
1104                 if (!sprev)
1105                         return -EIO;
1106                 mt_count = -mt_count;
1107         }
1108
1109         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1110                 tape->valid = 0;
1111                 if (test_and_clear_bit(ilog2(IDE_AFLAG_FILEMARK),
1112                                        &drive->atapi_flags))
1113                         ++count;
1114                 ide_tape_discard_merge_buffer(drive, 0);
1115         }
1116
1117         switch (mt_op) {
1118         case MTFSF:
1119         case MTBSF:
1120                 idetape_create_space_cmd(&pc, mt_count - count,
1121                                          IDETAPE_SPACE_OVER_FILEMARK);
1122                 return ide_queue_pc_tail(drive, disk, &pc);
1123         case MTFSFM:
1124         case MTBSFM:
1125                 if (!sprev)
1126                         return -EIO;
1127                 retval = idetape_space_over_filemarks(drive, MTFSF,
1128                                                       mt_count - count);
1129                 if (retval)
1130                         return retval;
1131                 count = (MTBSFM == mt_op ? 1 : -1);
1132                 return idetape_space_over_filemarks(drive, MTFSF, count);
1133         default:
1134                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1135                                 mt_op);
1136                 return -EIO;
1137         }
1138 }
1139
1140 /*
1141  * Our character device read / write functions.
1142  *
1143  * The tape is optimized to maximize throughput when it is transferring an
1144  * integral number of the "continuous transfer limit", which is a parameter of
1145  * the specific tape (26kB on my particular tape, 32kB for Onstream).
1146  *
1147  * As of version 1.3 of the driver, the character device provides an abstract
1148  * continuous view of the media - any mix of block sizes (even 1 byte) on the
1149  * same backup/restore procedure is supported. The driver will internally
1150  * convert the requests to the recommended transfer unit, so that an unmatch
1151  * between the user's block size to the recommended size will only result in a
1152  * (slightly) increased driver overhead, but will no longer hit performance.
1153  * This is not applicable to Onstream.
1154  */
1155 static ssize_t idetape_chrdev_read(struct file *file, char __user *buf,
1156                                    size_t count, loff_t *ppos)
1157 {
1158         struct ide_tape_obj *tape = file->private_data;
1159         ide_drive_t *drive = tape->drive;
1160         size_t done = 0;
1161         ssize_t ret = 0;
1162         int rc;
1163
1164         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1165
1166         if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1167                 if (test_bit(ilog2(IDE_AFLAG_DETECT_BS), &drive->atapi_flags))
1168                         if (count > tape->blk_size &&
1169                             (count % tape->blk_size) == 0)
1170                                 tape->user_bs_factor = count / tape->blk_size;
1171         }
1172
1173         rc = idetape_init_rw(drive, IDETAPE_DIR_READ);
1174         if (rc < 0)
1175                 return rc;
1176
1177         while (done < count) {
1178                 size_t todo;
1179
1180                 /* refill if staging buffer is empty */
1181                 if (!tape->valid) {
1182                         /* If we are at a filemark, nothing more to read */
1183                         if (test_bit(ilog2(IDE_AFLAG_FILEMARK),
1184                                      &drive->atapi_flags))
1185                                 break;
1186                         /* read */
1187                         if (idetape_queue_rw_tail(drive, REQ_IDETAPE_READ,
1188                                                   tape->buffer_size) <= 0)
1189                                 break;
1190                 }
1191
1192                 /* copy out */
1193                 todo = min_t(size_t, count - done, tape->valid);
1194                 if (copy_to_user(buf + done, tape->cur, todo))
1195                         ret = -EFAULT;
1196
1197                 tape->cur += todo;
1198                 tape->valid -= todo;
1199                 done += todo;
1200         }
1201
1202         if (!done && test_bit(ilog2(IDE_AFLAG_FILEMARK), &drive->atapi_flags)) {
1203                 debug_log(DBG_SENSE, "%s: spacing over filemark\n", tape->name);
1204
1205                 idetape_space_over_filemarks(drive, MTFSF, 1);
1206                 return 0;
1207         }
1208
1209         return ret ? ret : done;
1210 }
1211
1212 static ssize_t idetape_chrdev_write(struct file *file, const char __user *buf,
1213                                      size_t count, loff_t *ppos)
1214 {
1215         struct ide_tape_obj *tape = file->private_data;
1216         ide_drive_t *drive = tape->drive;
1217         size_t done = 0;
1218         ssize_t ret = 0;
1219         int rc;
1220
1221         /* The drive is write protected. */
1222         if (tape->write_prot)
1223                 return -EACCES;
1224
1225         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1226
1227         /* Initialize write operation */
1228         rc = idetape_init_rw(drive, IDETAPE_DIR_WRITE);
1229         if (rc < 0)
1230                 return rc;
1231
1232         while (done < count) {
1233                 size_t todo;
1234
1235                 /* flush if staging buffer is full */
1236                 if (tape->valid == tape->buffer_size &&
1237                     idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE,
1238                                           tape->buffer_size) <= 0)
1239                         return rc;
1240
1241                 /* copy in */
1242                 todo = min_t(size_t, count - done,
1243                              tape->buffer_size - tape->valid);
1244                 if (copy_from_user(tape->cur, buf + done, todo))
1245                         ret = -EFAULT;
1246
1247                 tape->cur += todo;
1248                 tape->valid += todo;
1249                 done += todo;
1250         }
1251
1252         return ret ? ret : done;
1253 }
1254
1255 static int idetape_write_filemark(ide_drive_t *drive)
1256 {
1257         struct ide_tape_obj *tape = drive->driver_data;
1258         struct ide_atapi_pc pc;
1259
1260         /* Write a filemark */
1261         idetape_create_write_filemark_cmd(drive, &pc, 1);
1262         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1263                 printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
1264                 return -EIO;
1265         }
1266         return 0;
1267 }
1268
1269 /*
1270  * Called from idetape_chrdev_ioctl when the general mtio MTIOCTOP ioctl is
1271  * requested.
1272  *
1273  * Note: MTBSF and MTBSFM are not supported when the tape doesn't support
1274  * spacing over filemarks in the reverse direction. In this case, MTFSFM is also
1275  * usually not supported.
1276  *
1277  * The following commands are currently not supported:
1278  *
1279  * MTFSS, MTBSS, MTWSM, MTSETDENSITY, MTSETDRVBUFFER, MT_ST_BOOLEANS,
1280  * MT_ST_WRITE_THRESHOLD.
1281  */
1282 static int idetape_mtioctop(ide_drive_t *drive, short mt_op, int mt_count)
1283 {
1284         idetape_tape_t *tape = drive->driver_data;
1285         struct gendisk *disk = tape->disk;
1286         struct ide_atapi_pc pc;
1287         int i, retval;
1288
1289         debug_log(DBG_ERR, "Handling MTIOCTOP ioctl: mt_op=%d, mt_count=%d\n",
1290                         mt_op, mt_count);
1291
1292         switch (mt_op) {
1293         case MTFSF:
1294         case MTFSFM:
1295         case MTBSF:
1296         case MTBSFM:
1297                 if (!mt_count)
1298                         return 0;
1299                 return idetape_space_over_filemarks(drive, mt_op, mt_count);
1300         default:
1301                 break;
1302         }
1303
1304         switch (mt_op) {
1305         case MTWEOF:
1306                 if (tape->write_prot)
1307                         return -EACCES;
1308                 ide_tape_discard_merge_buffer(drive, 1);
1309                 for (i = 0; i < mt_count; i++) {
1310                         retval = idetape_write_filemark(drive);
1311                         if (retval)
1312                                 return retval;
1313                 }
1314                 return 0;
1315         case MTREW:
1316                 ide_tape_discard_merge_buffer(drive, 0);
1317                 if (idetape_rewind_tape(drive))
1318                         return -EIO;
1319                 return 0;
1320         case MTLOAD:
1321                 ide_tape_discard_merge_buffer(drive, 0);
1322                 return ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
1323         case MTUNLOAD:
1324         case MTOFFL:
1325                 /*
1326                  * If door is locked, attempt to unlock before
1327                  * attempting to eject.
1328                  */
1329                 if (tape->door_locked) {
1330                         if (!ide_set_media_lock(drive, disk, 0))
1331                                 tape->door_locked = DOOR_UNLOCKED;
1332                 }
1333                 ide_tape_discard_merge_buffer(drive, 0);
1334                 retval = ide_do_start_stop(drive, disk, !IDETAPE_LU_LOAD_MASK);
1335                 if (!retval)
1336                         clear_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT),
1337                                   &drive->atapi_flags);
1338                 return retval;
1339         case MTNOP:
1340                 ide_tape_discard_merge_buffer(drive, 0);
1341                 return idetape_flush_tape_buffers(drive);
1342         case MTRETEN:
1343                 ide_tape_discard_merge_buffer(drive, 0);
1344                 return ide_do_start_stop(drive, disk,
1345                         IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
1346         case MTEOM:
1347                 idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
1348                 return ide_queue_pc_tail(drive, disk, &pc);
1349         case MTERASE:
1350                 (void)idetape_rewind_tape(drive);
1351                 idetape_create_erase_cmd(&pc);
1352                 return ide_queue_pc_tail(drive, disk, &pc);
1353         case MTSETBLK:
1354                 if (mt_count) {
1355                         if (mt_count < tape->blk_size ||
1356                             mt_count % tape->blk_size)
1357                                 return -EIO;
1358                         tape->user_bs_factor = mt_count / tape->blk_size;
1359                         clear_bit(ilog2(IDE_AFLAG_DETECT_BS),
1360                                   &drive->atapi_flags);
1361                 } else
1362                         set_bit(ilog2(IDE_AFLAG_DETECT_BS),
1363                                 &drive->atapi_flags);
1364                 return 0;
1365         case MTSEEK:
1366                 ide_tape_discard_merge_buffer(drive, 0);
1367                 return idetape_position_tape(drive,
1368                         mt_count * tape->user_bs_factor, tape->partition, 0);
1369         case MTSETPART:
1370                 ide_tape_discard_merge_buffer(drive, 0);
1371                 return idetape_position_tape(drive, 0, mt_count, 0);
1372         case MTFSR:
1373         case MTBSR:
1374         case MTLOCK:
1375                 retval = ide_set_media_lock(drive, disk, 1);
1376                 if (retval)
1377                         return retval;
1378                 tape->door_locked = DOOR_EXPLICITLY_LOCKED;
1379                 return 0;
1380         case MTUNLOCK:
1381                 retval = ide_set_media_lock(drive, disk, 0);
1382                 if (retval)
1383                         return retval;
1384                 tape->door_locked = DOOR_UNLOCKED;
1385                 return 0;
1386         default:
1387                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1388                                 mt_op);
1389                 return -EIO;
1390         }
1391 }
1392
1393 /*
1394  * Our character device ioctls. General mtio.h magnetic io commands are
1395  * supported here, and not in the corresponding block interface. Our own
1396  * ide-tape ioctls are supported on both interfaces.
1397  */
1398 static int idetape_chrdev_ioctl(struct inode *inode, struct file *file,
1399                                 unsigned int cmd, unsigned long arg)
1400 {
1401         struct ide_tape_obj *tape = file->private_data;
1402         ide_drive_t *drive = tape->drive;
1403         struct mtop mtop;
1404         struct mtget mtget;
1405         struct mtpos mtpos;
1406         int block_offset = 0, position = tape->first_frame;
1407         void __user *argp = (void __user *)arg;
1408
1409         debug_log(DBG_CHRDEV, "Enter %s, cmd=%u\n", __func__, cmd);
1410
1411         if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1412                 ide_tape_flush_merge_buffer(drive);
1413                 idetape_flush_tape_buffers(drive);
1414         }
1415         if (cmd == MTIOCGET || cmd == MTIOCPOS) {
1416                 block_offset = tape->valid /
1417                         (tape->blk_size * tape->user_bs_factor);
1418                 position = idetape_read_position(drive);
1419                 if (position < 0)
1420                         return -EIO;
1421         }
1422         switch (cmd) {
1423         case MTIOCTOP:
1424                 if (copy_from_user(&mtop, argp, sizeof(struct mtop)))
1425                         return -EFAULT;
1426                 return idetape_mtioctop(drive, mtop.mt_op, mtop.mt_count);
1427         case MTIOCGET:
1428                 memset(&mtget, 0, sizeof(struct mtget));
1429                 mtget.mt_type = MT_ISSCSI2;
1430                 mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
1431                 mtget.mt_dsreg =
1432                         ((tape->blk_size * tape->user_bs_factor)
1433                          << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
1434
1435                 if (tape->drv_write_prot)
1436                         mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
1437
1438                 if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
1439                         return -EFAULT;
1440                 return 0;
1441         case MTIOCPOS:
1442                 mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
1443                 if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
1444                         return -EFAULT;
1445                 return 0;
1446         default:
1447                 if (tape->chrdev_dir == IDETAPE_DIR_READ)
1448                         ide_tape_discard_merge_buffer(drive, 1);
1449                 return idetape_blkdev_ioctl(drive, cmd, arg);
1450         }
1451 }
1452
1453 /*
1454  * Do a mode sense page 0 with block descriptor and if it succeeds set the tape
1455  * block size with the reported value.
1456  */
1457 static void ide_tape_get_bsize_from_bdesc(ide_drive_t *drive)
1458 {
1459         idetape_tape_t *tape = drive->driver_data;
1460         struct ide_atapi_pc pc;
1461
1462         idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
1463         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1464                 printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
1465                 if (tape->blk_size == 0) {
1466                         printk(KERN_WARNING "ide-tape: Cannot deal with zero "
1467                                             "block size, assuming 32k\n");
1468                         tape->blk_size = 32768;
1469                 }
1470                 return;
1471         }
1472         tape->blk_size = (pc.buf[4 + 5] << 16) +
1473                                 (pc.buf[4 + 6] << 8)  +
1474                                  pc.buf[4 + 7];
1475         tape->drv_write_prot = (pc.buf[2] & 0x80) >> 7;
1476 }
1477
1478 static int idetape_chrdev_open(struct inode *inode, struct file *filp)
1479 {
1480         unsigned int minor = iminor(inode), i = minor & ~0xc0;
1481         ide_drive_t *drive;
1482         idetape_tape_t *tape;
1483         int retval;
1484
1485         if (i >= MAX_HWIFS * MAX_DRIVES)
1486                 return -ENXIO;
1487
1488         lock_kernel();
1489         tape = ide_tape_get(NULL, true, i);
1490         if (!tape) {
1491                 unlock_kernel();
1492                 return -ENXIO;
1493         }
1494
1495         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1496
1497         /*
1498          * We really want to do nonseekable_open(inode, filp); here, but some
1499          * versions of tar incorrectly call lseek on tapes and bail out if that
1500          * fails.  So we disallow pread() and pwrite(), but permit lseeks.
1501          */
1502         filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
1503
1504         drive = tape->drive;
1505
1506         filp->private_data = tape;
1507
1508         if (test_and_set_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags)) {
1509                 retval = -EBUSY;
1510                 goto out_put_tape;
1511         }
1512
1513         retval = idetape_wait_ready(drive, 60 * HZ);
1514         if (retval) {
1515                 clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1516                 printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
1517                 goto out_put_tape;
1518         }
1519
1520         idetape_read_position(drive);
1521         if (!test_bit(ilog2(IDE_AFLAG_ADDRESS_VALID), &drive->atapi_flags))
1522                 (void)idetape_rewind_tape(drive);
1523
1524         /* Read block size and write protect status from drive. */
1525         ide_tape_get_bsize_from_bdesc(drive);
1526
1527         /* Set write protect flag if device is opened as read-only. */
1528         if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
1529                 tape->write_prot = 1;
1530         else
1531                 tape->write_prot = tape->drv_write_prot;
1532
1533         /* Make sure drive isn't write protected if user wants to write. */
1534         if (tape->write_prot) {
1535                 if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
1536                     (filp->f_flags & O_ACCMODE) == O_RDWR) {
1537                         clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1538                         retval = -EROFS;
1539                         goto out_put_tape;
1540                 }
1541         }
1542
1543         /* Lock the tape drive door so user can't eject. */
1544         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1545                 if (!ide_set_media_lock(drive, tape->disk, 1)) {
1546                         if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
1547                                 tape->door_locked = DOOR_LOCKED;
1548                 }
1549         }
1550         unlock_kernel();
1551         return 0;
1552
1553 out_put_tape:
1554         ide_tape_put(tape);
1555         unlock_kernel();
1556         return retval;
1557 }
1558
1559 static void idetape_write_release(ide_drive_t *drive, unsigned int minor)
1560 {
1561         idetape_tape_t *tape = drive->driver_data;
1562
1563         ide_tape_flush_merge_buffer(drive);
1564         tape->buf = kmalloc(tape->buffer_size, GFP_KERNEL);
1565         if (tape->buf != NULL) {
1566                 idetape_pad_zeros(drive, tape->blk_size *
1567                                 (tape->user_bs_factor - 1));
1568                 kfree(tape->buf);
1569                 tape->buf = NULL;
1570         }
1571         idetape_write_filemark(drive);
1572         idetape_flush_tape_buffers(drive);
1573         idetape_flush_tape_buffers(drive);
1574 }
1575
1576 static int idetape_chrdev_release(struct inode *inode, struct file *filp)
1577 {
1578         struct ide_tape_obj *tape = filp->private_data;
1579         ide_drive_t *drive = tape->drive;
1580         unsigned int minor = iminor(inode);
1581
1582         lock_kernel();
1583         tape = drive->driver_data;
1584
1585         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1586
1587         if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
1588                 idetape_write_release(drive, minor);
1589         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1590                 if (minor < 128)
1591                         ide_tape_discard_merge_buffer(drive, 1);
1592         }
1593
1594         if (minor < 128 && test_bit(ilog2(IDE_AFLAG_MEDIUM_PRESENT),
1595                                     &drive->atapi_flags))
1596                 (void) idetape_rewind_tape(drive);
1597
1598         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1599                 if (tape->door_locked == DOOR_LOCKED) {
1600                         if (!ide_set_media_lock(drive, tape->disk, 0))
1601                                 tape->door_locked = DOOR_UNLOCKED;
1602                 }
1603         }
1604         clear_bit(ilog2(IDE_AFLAG_BUSY), &drive->atapi_flags);
1605         ide_tape_put(tape);
1606         unlock_kernel();
1607         return 0;
1608 }
1609
1610 static void idetape_get_inquiry_results(ide_drive_t *drive)
1611 {
1612         idetape_tape_t *tape = drive->driver_data;
1613         struct ide_atapi_pc pc;
1614         u8 pc_buf[256];
1615         char fw_rev[4], vendor_id[8], product_id[16];
1616
1617         idetape_create_inquiry_cmd(&pc);
1618         pc.buf = &pc_buf[0];
1619         pc.buf_size = sizeof(pc_buf);
1620
1621         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1622                 printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
1623                                 tape->name);
1624                 return;
1625         }
1626         memcpy(vendor_id, &pc.buf[8], 8);
1627         memcpy(product_id, &pc.buf[16], 16);
1628         memcpy(fw_rev, &pc.buf[32], 4);
1629
1630         ide_fixstring(vendor_id, 8, 0);
1631         ide_fixstring(product_id, 16, 0);
1632         ide_fixstring(fw_rev, 4, 0);
1633
1634         printk(KERN_INFO "ide-tape: %s <-> %s: %.8s %.16s rev %.4s\n",
1635                         drive->name, tape->name, vendor_id, product_id, fw_rev);
1636 }
1637
1638 /*
1639  * Ask the tape about its various parameters. In particular, we will adjust our
1640  * data transfer buffer size to the recommended value as returned by the tape.
1641  */
1642 static void idetape_get_mode_sense_results(ide_drive_t *drive)
1643 {
1644         idetape_tape_t *tape = drive->driver_data;
1645         struct ide_atapi_pc pc;
1646         u8 *caps;
1647         u8 speed, max_speed;
1648
1649         idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
1650         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1651                 printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
1652                                 " some default values\n");
1653                 tape->blk_size = 512;
1654                 put_unaligned(52,   (u16 *)&tape->caps[12]);
1655                 put_unaligned(540,  (u16 *)&tape->caps[14]);
1656                 put_unaligned(6*52, (u16 *)&tape->caps[16]);
1657                 return;
1658         }
1659         caps = pc.buf + 4 + pc.buf[3];
1660
1661         /* convert to host order and save for later use */
1662         speed = be16_to_cpup((__be16 *)&caps[14]);
1663         max_speed = be16_to_cpup((__be16 *)&caps[8]);
1664
1665         *(u16 *)&caps[8] = max_speed;
1666         *(u16 *)&caps[12] = be16_to_cpup((__be16 *)&caps[12]);
1667         *(u16 *)&caps[14] = speed;
1668         *(u16 *)&caps[16] = be16_to_cpup((__be16 *)&caps[16]);
1669
1670         if (!speed) {
1671                 printk(KERN_INFO "ide-tape: %s: invalid tape speed "
1672                                 "(assuming 650KB/sec)\n", drive->name);
1673                 *(u16 *)&caps[14] = 650;
1674         }
1675         if (!max_speed) {
1676                 printk(KERN_INFO "ide-tape: %s: invalid max_speed "
1677                                 "(assuming 650KB/sec)\n", drive->name);
1678                 *(u16 *)&caps[8] = 650;
1679         }
1680
1681         memcpy(&tape->caps, caps, 20);
1682
1683         /* device lacks locking support according to capabilities page */
1684         if ((caps[6] & 1) == 0)
1685                 drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
1686
1687         if (caps[7] & 0x02)
1688                 tape->blk_size = 512;
1689         else if (caps[7] & 0x04)
1690                 tape->blk_size = 1024;
1691 }
1692
1693 #ifdef CONFIG_IDE_PROC_FS
1694 #define ide_tape_devset_get(name, field) \
1695 static int get_##name(ide_drive_t *drive) \
1696 { \
1697         idetape_tape_t *tape = drive->driver_data; \
1698         return tape->field; \
1699 }
1700
1701 #define ide_tape_devset_set(name, field) \
1702 static int set_##name(ide_drive_t *drive, int arg) \
1703 { \
1704         idetape_tape_t *tape = drive->driver_data; \
1705         tape->field = arg; \
1706         return 0; \
1707 }
1708
1709 #define ide_tape_devset_rw_field(_name, _field) \
1710 ide_tape_devset_get(_name, _field) \
1711 ide_tape_devset_set(_name, _field) \
1712 IDE_DEVSET(_name, DS_SYNC, get_##_name, set_##_name)
1713
1714 #define ide_tape_devset_r_field(_name, _field) \
1715 ide_tape_devset_get(_name, _field) \
1716 IDE_DEVSET(_name, 0, get_##_name, NULL)
1717
1718 static int mulf_tdsc(ide_drive_t *drive)        { return 1000; }
1719 static int divf_tdsc(ide_drive_t *drive)        { return   HZ; }
1720 static int divf_buffer(ide_drive_t *drive)      { return    2; }
1721 static int divf_buffer_size(ide_drive_t *drive) { return 1024; }
1722
1723 ide_devset_rw_flag(dsc_overlap, IDE_DFLAG_DSC_OVERLAP);
1724
1725 ide_tape_devset_rw_field(debug_mask, debug_mask);
1726 ide_tape_devset_rw_field(tdsc, best_dsc_rw_freq);
1727
1728 ide_tape_devset_r_field(avg_speed, avg_speed);
1729 ide_tape_devset_r_field(speed, caps[14]);
1730 ide_tape_devset_r_field(buffer, caps[16]);
1731 ide_tape_devset_r_field(buffer_size, buffer_size);
1732
1733 static const struct ide_proc_devset idetape_settings[] = {
1734         __IDE_PROC_DEVSET(avg_speed,    0, 0xffff, NULL, NULL),
1735         __IDE_PROC_DEVSET(buffer,       0, 0xffff, NULL, divf_buffer),
1736         __IDE_PROC_DEVSET(buffer_size,  0, 0xffff, NULL, divf_buffer_size),
1737         __IDE_PROC_DEVSET(debug_mask,   0, 0xffff, NULL, NULL),
1738         __IDE_PROC_DEVSET(dsc_overlap,  0,      1, NULL, NULL),
1739         __IDE_PROC_DEVSET(speed,        0, 0xffff, NULL, NULL),
1740         __IDE_PROC_DEVSET(tdsc,         IDETAPE_DSC_RW_MIN, IDETAPE_DSC_RW_MAX,
1741                                         mulf_tdsc, divf_tdsc),
1742         { NULL },
1743 };
1744 #endif
1745
1746 /*
1747  * The function below is called to:
1748  *
1749  * 1. Initialize our various state variables.
1750  * 2. Ask the tape for its capabilities.
1751  * 3. Allocate a buffer which will be used for data transfer. The buffer size
1752  * is chosen based on the recommendation which we received in step 2.
1753  *
1754  * Note that at this point ide.c already assigned us an irq, so that we can
1755  * queue requests here and wait for their completion.
1756  */
1757 static void idetape_setup(ide_drive_t *drive, idetape_tape_t *tape, int minor)
1758 {
1759         unsigned long t;
1760         int speed;
1761         int buffer_size;
1762         u16 *ctl = (u16 *)&tape->caps[12];
1763
1764         drive->pc_callback       = ide_tape_callback;
1765
1766         drive->dev_flags |= IDE_DFLAG_DSC_OVERLAP;
1767
1768         if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
1769                 printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
1770                                  tape->name);
1771                 drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1772         }
1773
1774         /* Seagate Travan drives do not support DSC overlap. */
1775         if (strstr((char *)&drive->id[ATA_ID_PROD], "Seagate STT3401"))
1776                 drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1777
1778         tape->minor = minor;
1779         tape->name[0] = 'h';
1780         tape->name[1] = 't';
1781         tape->name[2] = '0' + minor;
1782         tape->chrdev_dir = IDETAPE_DIR_NONE;
1783
1784         idetape_get_inquiry_results(drive);
1785         idetape_get_mode_sense_results(drive);
1786         ide_tape_get_bsize_from_bdesc(drive);
1787         tape->user_bs_factor = 1;
1788         tape->buffer_size = *ctl * tape->blk_size;
1789         while (tape->buffer_size > 0xffff) {
1790                 printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
1791                 *ctl /= 2;
1792                 tape->buffer_size = *ctl * tape->blk_size;
1793         }
1794         buffer_size = tape->buffer_size;
1795
1796         /* select the "best" DSC read/write polling freq */
1797         speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
1798
1799         t = (IDETAPE_FIFO_THRESHOLD * tape->buffer_size * HZ) / (speed * 1000);
1800
1801         /*
1802          * Ensure that the number we got makes sense; limit it within
1803          * IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
1804          */
1805         tape->best_dsc_rw_freq = clamp_t(unsigned long, t, IDETAPE_DSC_RW_MIN,
1806                                          IDETAPE_DSC_RW_MAX);
1807         printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
1808                 "%lums tDSC%s\n",
1809                 drive->name, tape->name, *(u16 *)&tape->caps[14],
1810                 (*(u16 *)&tape->caps[16] * 512) / tape->buffer_size,
1811                 tape->buffer_size / 1024,
1812                 tape->best_dsc_rw_freq * 1000 / HZ,
1813                 (drive->dev_flags & IDE_DFLAG_USING_DMA) ? ", DMA" : "");
1814
1815         ide_proc_register_driver(drive, tape->driver);
1816 }
1817
1818 static void ide_tape_remove(ide_drive_t *drive)
1819 {
1820         idetape_tape_t *tape = drive->driver_data;
1821
1822         ide_proc_unregister_driver(drive, tape->driver);
1823         device_del(&tape->dev);
1824         ide_unregister_region(tape->disk);
1825
1826         mutex_lock(&idetape_ref_mutex);
1827         put_device(&tape->dev);
1828         mutex_unlock(&idetape_ref_mutex);
1829 }
1830
1831 static void ide_tape_release(struct device *dev)
1832 {
1833         struct ide_tape_obj *tape = to_ide_drv(dev, ide_tape_obj);
1834         ide_drive_t *drive = tape->drive;
1835         struct gendisk *g = tape->disk;
1836
1837         BUG_ON(tape->valid);
1838
1839         drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
1840         drive->driver_data = NULL;
1841         device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
1842         device_destroy(idetape_sysfs_class,
1843                         MKDEV(IDETAPE_MAJOR, tape->minor + 128));
1844         idetape_devs[tape->minor] = NULL;
1845         g->private_data = NULL;
1846         put_disk(g);
1847         kfree(tape);
1848 }
1849
1850 #ifdef CONFIG_IDE_PROC_FS
1851 static int proc_idetape_read_name
1852         (char *page, char **start, off_t off, int count, int *eof, void *data)
1853 {
1854         ide_drive_t     *drive = (ide_drive_t *) data;
1855         idetape_tape_t  *tape = drive->driver_data;
1856         char            *out = page;
1857         int             len;
1858
1859         len = sprintf(out, "%s\n", tape->name);
1860         PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
1861 }
1862
1863 static ide_proc_entry_t idetape_proc[] = {
1864         { "capacity",   S_IFREG|S_IRUGO,        proc_ide_read_capacity, NULL },
1865         { "name",       S_IFREG|S_IRUGO,        proc_idetape_read_name, NULL },
1866         { NULL, 0, NULL, NULL }
1867 };
1868
1869 static ide_proc_entry_t *ide_tape_proc_entries(ide_drive_t *drive)
1870 {
1871         return idetape_proc;
1872 }
1873
1874 static const struct ide_proc_devset *ide_tape_proc_devsets(ide_drive_t *drive)
1875 {
1876         return idetape_settings;
1877 }
1878 #endif
1879
1880 static int ide_tape_probe(ide_drive_t *);
1881
1882 static struct ide_driver idetape_driver = {
1883         .gen_driver = {
1884                 .owner          = THIS_MODULE,
1885                 .name           = "ide-tape",
1886                 .bus            = &ide_bus_type,
1887         },
1888         .probe                  = ide_tape_probe,
1889         .remove                 = ide_tape_remove,
1890         .version                = IDETAPE_VERSION,
1891         .do_request             = idetape_do_request,
1892 #ifdef CONFIG_IDE_PROC_FS
1893         .proc_entries           = ide_tape_proc_entries,
1894         .proc_devsets           = ide_tape_proc_devsets,
1895 #endif
1896 };
1897
1898 /* Our character device supporting functions, passed to register_chrdev. */
1899 static const struct file_operations idetape_fops = {
1900         .owner          = THIS_MODULE,
1901         .read           = idetape_chrdev_read,
1902         .write          = idetape_chrdev_write,
1903         .ioctl          = idetape_chrdev_ioctl,
1904         .open           = idetape_chrdev_open,
1905         .release        = idetape_chrdev_release,
1906 };
1907
1908 static int idetape_open(struct block_device *bdev, fmode_t mode)
1909 {
1910         struct ide_tape_obj *tape = ide_tape_get(bdev->bd_disk, false, 0);
1911
1912         if (!tape)
1913                 return -ENXIO;
1914
1915         return 0;
1916 }
1917
1918 static int idetape_release(struct gendisk *disk, fmode_t mode)
1919 {
1920         struct ide_tape_obj *tape = ide_drv_g(disk, ide_tape_obj);
1921
1922         ide_tape_put(tape);
1923         return 0;
1924 }
1925
1926 static int idetape_ioctl(struct block_device *bdev, fmode_t mode,
1927                         unsigned int cmd, unsigned long arg)
1928 {
1929         struct ide_tape_obj *tape = ide_drv_g(bdev->bd_disk, ide_tape_obj);
1930         ide_drive_t *drive = tape->drive;
1931         int err = generic_ide_ioctl(drive, bdev, cmd, arg);
1932         if (err == -EINVAL)
1933                 err = idetape_blkdev_ioctl(drive, cmd, arg);
1934         return err;
1935 }
1936
1937 static struct block_device_operations idetape_block_ops = {
1938         .owner          = THIS_MODULE,
1939         .open           = idetape_open,
1940         .release        = idetape_release,
1941         .locked_ioctl   = idetape_ioctl,
1942 };
1943
1944 static int ide_tape_probe(ide_drive_t *drive)
1945 {
1946         idetape_tape_t *tape;
1947         struct gendisk *g;
1948         int minor;
1949
1950         if (!strstr("ide-tape", drive->driver_req))
1951                 goto failed;
1952
1953         if (drive->media != ide_tape)
1954                 goto failed;
1955
1956         if ((drive->dev_flags & IDE_DFLAG_ID_READ) &&
1957             ide_check_atapi_device(drive, DRV_NAME) == 0) {
1958                 printk(KERN_ERR "ide-tape: %s: not supported by this version of"
1959                                 " the driver\n", drive->name);
1960                 goto failed;
1961         }
1962         tape = kzalloc(sizeof(idetape_tape_t), GFP_KERNEL);
1963         if (tape == NULL) {
1964                 printk(KERN_ERR "ide-tape: %s: Can't allocate a tape struct\n",
1965                                 drive->name);
1966                 goto failed;
1967         }
1968
1969         g = alloc_disk(1 << PARTN_BITS);
1970         if (!g)
1971                 goto out_free_tape;
1972
1973         ide_init_disk(g, drive);
1974
1975         tape->dev.parent = &drive->gendev;
1976         tape->dev.release = ide_tape_release;
1977         dev_set_name(&tape->dev, dev_name(&drive->gendev));
1978
1979         if (device_register(&tape->dev))
1980                 goto out_free_disk;
1981
1982         tape->drive = drive;
1983         tape->driver = &idetape_driver;
1984         tape->disk = g;
1985
1986         g->private_data = &tape->driver;
1987
1988         drive->driver_data = tape;
1989
1990         mutex_lock(&idetape_ref_mutex);
1991         for (minor = 0; idetape_devs[minor]; minor++)
1992                 ;
1993         idetape_devs[minor] = tape;
1994         mutex_unlock(&idetape_ref_mutex);
1995
1996         idetape_setup(drive, tape, minor);
1997
1998         device_create(idetape_sysfs_class, &drive->gendev,
1999                       MKDEV(IDETAPE_MAJOR, minor), NULL, "%s", tape->name);
2000         device_create(idetape_sysfs_class, &drive->gendev,
2001                       MKDEV(IDETAPE_MAJOR, minor + 128), NULL,
2002                       "n%s", tape->name);
2003
2004         g->fops = &idetape_block_ops;
2005         ide_register_region(g);
2006
2007         return 0;
2008
2009 out_free_disk:
2010         put_disk(g);
2011 out_free_tape:
2012         kfree(tape);
2013 failed:
2014         return -ENODEV;
2015 }
2016
2017 static void __exit idetape_exit(void)
2018 {
2019         driver_unregister(&idetape_driver.gen_driver);
2020         class_destroy(idetape_sysfs_class);
2021         unregister_chrdev(IDETAPE_MAJOR, "ht");
2022 }
2023
2024 static int __init idetape_init(void)
2025 {
2026         int error = 1;
2027         idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
2028         if (IS_ERR(idetape_sysfs_class)) {
2029                 idetape_sysfs_class = NULL;
2030                 printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
2031                 error = -EBUSY;
2032                 goto out;
2033         }
2034
2035         if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
2036                 printk(KERN_ERR "ide-tape: Failed to register chrdev"
2037                                 " interface\n");
2038                 error = -EBUSY;
2039                 goto out_free_class;
2040         }
2041
2042         error = driver_register(&idetape_driver.gen_driver);
2043         if (error)
2044                 goto out_free_driver;
2045
2046         return 0;
2047
2048 out_free_driver:
2049         driver_unregister(&idetape_driver.gen_driver);
2050 out_free_class:
2051         class_destroy(idetape_sysfs_class);
2052 out:
2053         return error;
2054 }
2055
2056 MODULE_ALIAS("ide:*m-tape*");
2057 module_init(idetape_init);
2058 module_exit(idetape_exit);
2059 MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
2060 MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
2061 MODULE_LICENSE("GPL");