Merge rsync://rsync.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6
[linux-2.6] / drivers / block / pktcdvd.c
1 /*
2  * Copyright (C) 2000 Jens Axboe <axboe@suse.de>
3  * Copyright (C) 2001-2004 Peter Osterlund <petero2@telia.com>
4  *
5  * May be copied or modified under the terms of the GNU General Public
6  * License.  See linux/COPYING for more information.
7  *
8  * Packet writing layer for ATAPI and SCSI CD-RW, DVD+RW, DVD-RW and
9  * DVD-RAM devices.
10  *
11  * Theory of operation:
12  *
13  * At the lowest level, there is the standard driver for the CD/DVD device,
14  * typically ide-cd.c or sr.c. This driver can handle read and write requests,
15  * but it doesn't know anything about the special restrictions that apply to
16  * packet writing. One restriction is that write requests must be aligned to
17  * packet boundaries on the physical media, and the size of a write request
18  * must be equal to the packet size. Another restriction is that a
19  * GPCMD_FLUSH_CACHE command has to be issued to the drive before a read
20  * command, if the previous command was a write.
21  *
22  * The purpose of the packet writing driver is to hide these restrictions from
23  * higher layers, such as file systems, and present a block device that can be
24  * randomly read and written using 2kB-sized blocks.
25  *
26  * The lowest layer in the packet writing driver is the packet I/O scheduler.
27  * Its data is defined by the struct packet_iosched and includes two bio
28  * queues with pending read and write requests. These queues are processed
29  * by the pkt_iosched_process_queue() function. The write requests in this
30  * queue are already properly aligned and sized. This layer is responsible for
31  * issuing the flush cache commands and scheduling the I/O in a good order.
32  *
33  * The next layer transforms unaligned write requests to aligned writes. This
34  * transformation requires reading missing pieces of data from the underlying
35  * block device, assembling the pieces to full packets and queuing them to the
36  * packet I/O scheduler.
37  *
38  * At the top layer there is a custom make_request_fn function that forwards
39  * read requests directly to the iosched queue and puts write requests in the
40  * unaligned write queue. A kernel thread performs the necessary read
41  * gathering to convert the unaligned writes to aligned writes and then feeds
42  * them to the packet I/O scheduler.
43  *
44  *************************************************************************/
45
46 #define VERSION_CODE    "v0.2.0a 2004-07-14 Jens Axboe (axboe@suse.de) and petero2@telia.com"
47
48 #include <linux/pktcdvd.h>
49 #include <linux/config.h>
50 #include <linux/module.h>
51 #include <linux/types.h>
52 #include <linux/kernel.h>
53 #include <linux/kthread.h>
54 #include <linux/errno.h>
55 #include <linux/spinlock.h>
56 #include <linux/file.h>
57 #include <linux/proc_fs.h>
58 #include <linux/seq_file.h>
59 #include <linux/miscdevice.h>
60 #include <linux/suspend.h>
61 #include <scsi/scsi_cmnd.h>
62 #include <scsi/scsi_ioctl.h>
63
64 #include <asm/uaccess.h>
65
66 #if PACKET_DEBUG
67 #define DPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
68 #else
69 #define DPRINTK(fmt, args...)
70 #endif
71
72 #if PACKET_DEBUG > 1
73 #define VPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
74 #else
75 #define VPRINTK(fmt, args...)
76 #endif
77
78 #define MAX_SPEED 0xffff
79
80 #define ZONE(sector, pd) (((sector) + (pd)->offset) & ~((pd)->settings.size - 1))
81
82 static struct pktcdvd_device *pkt_devs[MAX_WRITERS];
83 static struct proc_dir_entry *pkt_proc;
84 static int pkt_major;
85 static struct semaphore ctl_mutex;      /* Serialize open/close/setup/teardown */
86 static mempool_t *psd_pool;
87
88
89 static void pkt_bio_finished(struct pktcdvd_device *pd)
90 {
91         BUG_ON(atomic_read(&pd->cdrw.pending_bios) <= 0);
92         if (atomic_dec_and_test(&pd->cdrw.pending_bios)) {
93                 VPRINTK("pktcdvd: queue empty\n");
94                 atomic_set(&pd->iosched.attention, 1);
95                 wake_up(&pd->wqueue);
96         }
97 }
98
99 static void pkt_bio_destructor(struct bio *bio)
100 {
101         kfree(bio->bi_io_vec);
102         kfree(bio);
103 }
104
105 static struct bio *pkt_bio_alloc(int nr_iovecs)
106 {
107         struct bio_vec *bvl = NULL;
108         struct bio *bio;
109
110         bio = kmalloc(sizeof(struct bio), GFP_KERNEL);
111         if (!bio)
112                 goto no_bio;
113         bio_init(bio);
114
115         bvl = kcalloc(nr_iovecs, sizeof(struct bio_vec), GFP_KERNEL);
116         if (!bvl)
117                 goto no_bvl;
118
119         bio->bi_max_vecs = nr_iovecs;
120         bio->bi_io_vec = bvl;
121         bio->bi_destructor = pkt_bio_destructor;
122
123         return bio;
124
125  no_bvl:
126         kfree(bio);
127  no_bio:
128         return NULL;
129 }
130
131 /*
132  * Allocate a packet_data struct
133  */
134 static struct packet_data *pkt_alloc_packet_data(void)
135 {
136         int i;
137         struct packet_data *pkt;
138
139         pkt = kzalloc(sizeof(struct packet_data), GFP_KERNEL);
140         if (!pkt)
141                 goto no_pkt;
142
143         pkt->w_bio = pkt_bio_alloc(PACKET_MAX_SIZE);
144         if (!pkt->w_bio)
145                 goto no_bio;
146
147         for (i = 0; i < PAGES_PER_PACKET; i++) {
148                 pkt->pages[i] = alloc_page(GFP_KERNEL|__GFP_ZERO);
149                 if (!pkt->pages[i])
150                         goto no_page;
151         }
152
153         spin_lock_init(&pkt->lock);
154
155         for (i = 0; i < PACKET_MAX_SIZE; i++) {
156                 struct bio *bio = pkt_bio_alloc(1);
157                 if (!bio)
158                         goto no_rd_bio;
159                 pkt->r_bios[i] = bio;
160         }
161
162         return pkt;
163
164 no_rd_bio:
165         for (i = 0; i < PACKET_MAX_SIZE; i++) {
166                 struct bio *bio = pkt->r_bios[i];
167                 if (bio)
168                         bio_put(bio);
169         }
170
171 no_page:
172         for (i = 0; i < PAGES_PER_PACKET; i++)
173                 if (pkt->pages[i])
174                         __free_page(pkt->pages[i]);
175         bio_put(pkt->w_bio);
176 no_bio:
177         kfree(pkt);
178 no_pkt:
179         return NULL;
180 }
181
182 /*
183  * Free a packet_data struct
184  */
185 static void pkt_free_packet_data(struct packet_data *pkt)
186 {
187         int i;
188
189         for (i = 0; i < PACKET_MAX_SIZE; i++) {
190                 struct bio *bio = pkt->r_bios[i];
191                 if (bio)
192                         bio_put(bio);
193         }
194         for (i = 0; i < PAGES_PER_PACKET; i++)
195                 __free_page(pkt->pages[i]);
196         bio_put(pkt->w_bio);
197         kfree(pkt);
198 }
199
200 static void pkt_shrink_pktlist(struct pktcdvd_device *pd)
201 {
202         struct packet_data *pkt, *next;
203
204         BUG_ON(!list_empty(&pd->cdrw.pkt_active_list));
205
206         list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_free_list, list) {
207                 pkt_free_packet_data(pkt);
208         }
209 }
210
211 static int pkt_grow_pktlist(struct pktcdvd_device *pd, int nr_packets)
212 {
213         struct packet_data *pkt;
214
215         INIT_LIST_HEAD(&pd->cdrw.pkt_free_list);
216         INIT_LIST_HEAD(&pd->cdrw.pkt_active_list);
217         spin_lock_init(&pd->cdrw.active_list_lock);
218         while (nr_packets > 0) {
219                 pkt = pkt_alloc_packet_data();
220                 if (!pkt) {
221                         pkt_shrink_pktlist(pd);
222                         return 0;
223                 }
224                 pkt->id = nr_packets;
225                 pkt->pd = pd;
226                 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
227                 nr_packets--;
228         }
229         return 1;
230 }
231
232 static void *pkt_rb_alloc(gfp_t gfp_mask, void *data)
233 {
234         return kmalloc(sizeof(struct pkt_rb_node), gfp_mask);
235 }
236
237 static void pkt_rb_free(void *ptr, void *data)
238 {
239         kfree(ptr);
240 }
241
242 static inline struct pkt_rb_node *pkt_rbtree_next(struct pkt_rb_node *node)
243 {
244         struct rb_node *n = rb_next(&node->rb_node);
245         if (!n)
246                 return NULL;
247         return rb_entry(n, struct pkt_rb_node, rb_node);
248 }
249
250 static inline void pkt_rbtree_erase(struct pktcdvd_device *pd, struct pkt_rb_node *node)
251 {
252         rb_erase(&node->rb_node, &pd->bio_queue);
253         mempool_free(node, pd->rb_pool);
254         pd->bio_queue_size--;
255         BUG_ON(pd->bio_queue_size < 0);
256 }
257
258 /*
259  * Find the first node in the pd->bio_queue rb tree with a starting sector >= s.
260  */
261 static struct pkt_rb_node *pkt_rbtree_find(struct pktcdvd_device *pd, sector_t s)
262 {
263         struct rb_node *n = pd->bio_queue.rb_node;
264         struct rb_node *next;
265         struct pkt_rb_node *tmp;
266
267         if (!n) {
268                 BUG_ON(pd->bio_queue_size > 0);
269                 return NULL;
270         }
271
272         for (;;) {
273                 tmp = rb_entry(n, struct pkt_rb_node, rb_node);
274                 if (s <= tmp->bio->bi_sector)
275                         next = n->rb_left;
276                 else
277                         next = n->rb_right;
278                 if (!next)
279                         break;
280                 n = next;
281         }
282
283         if (s > tmp->bio->bi_sector) {
284                 tmp = pkt_rbtree_next(tmp);
285                 if (!tmp)
286                         return NULL;
287         }
288         BUG_ON(s > tmp->bio->bi_sector);
289         return tmp;
290 }
291
292 /*
293  * Insert a node into the pd->bio_queue rb tree.
294  */
295 static void pkt_rbtree_insert(struct pktcdvd_device *pd, struct pkt_rb_node *node)
296 {
297         struct rb_node **p = &pd->bio_queue.rb_node;
298         struct rb_node *parent = NULL;
299         sector_t s = node->bio->bi_sector;
300         struct pkt_rb_node *tmp;
301
302         while (*p) {
303                 parent = *p;
304                 tmp = rb_entry(parent, struct pkt_rb_node, rb_node);
305                 if (s < tmp->bio->bi_sector)
306                         p = &(*p)->rb_left;
307                 else
308                         p = &(*p)->rb_right;
309         }
310         rb_link_node(&node->rb_node, parent, p);
311         rb_insert_color(&node->rb_node, &pd->bio_queue);
312         pd->bio_queue_size++;
313 }
314
315 /*
316  * Add a bio to a single linked list defined by its head and tail pointers.
317  */
318 static inline void pkt_add_list_last(struct bio *bio, struct bio **list_head, struct bio **list_tail)
319 {
320         bio->bi_next = NULL;
321         if (*list_tail) {
322                 BUG_ON((*list_head) == NULL);
323                 (*list_tail)->bi_next = bio;
324                 (*list_tail) = bio;
325         } else {
326                 BUG_ON((*list_head) != NULL);
327                 (*list_head) = bio;
328                 (*list_tail) = bio;
329         }
330 }
331
332 /*
333  * Remove and return the first bio from a single linked list defined by its
334  * head and tail pointers.
335  */
336 static inline struct bio *pkt_get_list_first(struct bio **list_head, struct bio **list_tail)
337 {
338         struct bio *bio;
339
340         if (*list_head == NULL)
341                 return NULL;
342
343         bio = *list_head;
344         *list_head = bio->bi_next;
345         if (*list_head == NULL)
346                 *list_tail = NULL;
347
348         bio->bi_next = NULL;
349         return bio;
350 }
351
352 /*
353  * Send a packet_command to the underlying block device and
354  * wait for completion.
355  */
356 static int pkt_generic_packet(struct pktcdvd_device *pd, struct packet_command *cgc)
357 {
358         char sense[SCSI_SENSE_BUFFERSIZE];
359         request_queue_t *q;
360         struct request *rq;
361         DECLARE_COMPLETION(wait);
362         int err = 0;
363
364         q = bdev_get_queue(pd->bdev);
365
366         rq = blk_get_request(q, (cgc->data_direction == CGC_DATA_WRITE) ? WRITE : READ,
367                              __GFP_WAIT);
368         rq->errors = 0;
369         rq->rq_disk = pd->bdev->bd_disk;
370         rq->bio = NULL;
371         rq->buffer = NULL;
372         rq->timeout = 60*HZ;
373         rq->data = cgc->buffer;
374         rq->data_len = cgc->buflen;
375         rq->sense = sense;
376         memset(sense, 0, sizeof(sense));
377         rq->sense_len = 0;
378         rq->flags |= REQ_BLOCK_PC | REQ_HARDBARRIER;
379         if (cgc->quiet)
380                 rq->flags |= REQ_QUIET;
381         memcpy(rq->cmd, cgc->cmd, CDROM_PACKET_SIZE);
382         if (sizeof(rq->cmd) > CDROM_PACKET_SIZE)
383                 memset(rq->cmd + CDROM_PACKET_SIZE, 0, sizeof(rq->cmd) - CDROM_PACKET_SIZE);
384
385         rq->ref_count++;
386         rq->flags |= REQ_NOMERGE;
387         rq->waiting = &wait;
388         rq->end_io = blk_end_sync_rq;
389         elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 1);
390         generic_unplug_device(q);
391         wait_for_completion(&wait);
392
393         if (rq->errors)
394                 err = -EIO;
395
396         blk_put_request(rq);
397         return err;
398 }
399
400 /*
401  * A generic sense dump / resolve mechanism should be implemented across
402  * all ATAPI + SCSI devices.
403  */
404 static void pkt_dump_sense(struct packet_command *cgc)
405 {
406         static char *info[9] = { "No sense", "Recovered error", "Not ready",
407                                  "Medium error", "Hardware error", "Illegal request",
408                                  "Unit attention", "Data protect", "Blank check" };
409         int i;
410         struct request_sense *sense = cgc->sense;
411
412         printk("pktcdvd:");
413         for (i = 0; i < CDROM_PACKET_SIZE; i++)
414                 printk(" %02x", cgc->cmd[i]);
415         printk(" - ");
416
417         if (sense == NULL) {
418                 printk("no sense\n");
419                 return;
420         }
421
422         printk("sense %02x.%02x.%02x", sense->sense_key, sense->asc, sense->ascq);
423
424         if (sense->sense_key > 8) {
425                 printk(" (INVALID)\n");
426                 return;
427         }
428
429         printk(" (%s)\n", info[sense->sense_key]);
430 }
431
432 /*
433  * flush the drive cache to media
434  */
435 static int pkt_flush_cache(struct pktcdvd_device *pd)
436 {
437         struct packet_command cgc;
438
439         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
440         cgc.cmd[0] = GPCMD_FLUSH_CACHE;
441         cgc.quiet = 1;
442
443         /*
444          * the IMMED bit -- we default to not setting it, although that
445          * would allow a much faster close, this is safer
446          */
447 #if 0
448         cgc.cmd[1] = 1 << 1;
449 #endif
450         return pkt_generic_packet(pd, &cgc);
451 }
452
453 /*
454  * speed is given as the normal factor, e.g. 4 for 4x
455  */
456 static int pkt_set_speed(struct pktcdvd_device *pd, unsigned write_speed, unsigned read_speed)
457 {
458         struct packet_command cgc;
459         struct request_sense sense;
460         int ret;
461
462         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
463         cgc.sense = &sense;
464         cgc.cmd[0] = GPCMD_SET_SPEED;
465         cgc.cmd[2] = (read_speed >> 8) & 0xff;
466         cgc.cmd[3] = read_speed & 0xff;
467         cgc.cmd[4] = (write_speed >> 8) & 0xff;
468         cgc.cmd[5] = write_speed & 0xff;
469
470         if ((ret = pkt_generic_packet(pd, &cgc)))
471                 pkt_dump_sense(&cgc);
472
473         return ret;
474 }
475
476 /*
477  * Queue a bio for processing by the low-level CD device. Must be called
478  * from process context.
479  */
480 static void pkt_queue_bio(struct pktcdvd_device *pd, struct bio *bio)
481 {
482         spin_lock(&pd->iosched.lock);
483         if (bio_data_dir(bio) == READ) {
484                 pkt_add_list_last(bio, &pd->iosched.read_queue,
485                                   &pd->iosched.read_queue_tail);
486         } else {
487                 pkt_add_list_last(bio, &pd->iosched.write_queue,
488                                   &pd->iosched.write_queue_tail);
489         }
490         spin_unlock(&pd->iosched.lock);
491
492         atomic_set(&pd->iosched.attention, 1);
493         wake_up(&pd->wqueue);
494 }
495
496 /*
497  * Process the queued read/write requests. This function handles special
498  * requirements for CDRW drives:
499  * - A cache flush command must be inserted before a read request if the
500  *   previous request was a write.
501  * - Switching between reading and writing is slow, so don't do it more often
502  *   than necessary.
503  * - Optimize for throughput at the expense of latency. This means that streaming
504  *   writes will never be interrupted by a read, but if the drive has to seek
505  *   before the next write, switch to reading instead if there are any pending
506  *   read requests.
507  * - Set the read speed according to current usage pattern. When only reading
508  *   from the device, it's best to use the highest possible read speed, but
509  *   when switching often between reading and writing, it's better to have the
510  *   same read and write speeds.
511  */
512 static void pkt_iosched_process_queue(struct pktcdvd_device *pd)
513 {
514         request_queue_t *q;
515
516         if (atomic_read(&pd->iosched.attention) == 0)
517                 return;
518         atomic_set(&pd->iosched.attention, 0);
519
520         q = bdev_get_queue(pd->bdev);
521
522         for (;;) {
523                 struct bio *bio;
524                 int reads_queued, writes_queued;
525
526                 spin_lock(&pd->iosched.lock);
527                 reads_queued = (pd->iosched.read_queue != NULL);
528                 writes_queued = (pd->iosched.write_queue != NULL);
529                 spin_unlock(&pd->iosched.lock);
530
531                 if (!reads_queued && !writes_queued)
532                         break;
533
534                 if (pd->iosched.writing) {
535                         int need_write_seek = 1;
536                         spin_lock(&pd->iosched.lock);
537                         bio = pd->iosched.write_queue;
538                         spin_unlock(&pd->iosched.lock);
539                         if (bio && (bio->bi_sector == pd->iosched.last_write))
540                                 need_write_seek = 0;
541                         if (need_write_seek && reads_queued) {
542                                 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
543                                         VPRINTK("pktcdvd: write, waiting\n");
544                                         break;
545                                 }
546                                 pkt_flush_cache(pd);
547                                 pd->iosched.writing = 0;
548                         }
549                 } else {
550                         if (!reads_queued && writes_queued) {
551                                 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
552                                         VPRINTK("pktcdvd: read, waiting\n");
553                                         break;
554                                 }
555                                 pd->iosched.writing = 1;
556                         }
557                 }
558
559                 spin_lock(&pd->iosched.lock);
560                 if (pd->iosched.writing) {
561                         bio = pkt_get_list_first(&pd->iosched.write_queue,
562                                                  &pd->iosched.write_queue_tail);
563                 } else {
564                         bio = pkt_get_list_first(&pd->iosched.read_queue,
565                                                  &pd->iosched.read_queue_tail);
566                 }
567                 spin_unlock(&pd->iosched.lock);
568
569                 if (!bio)
570                         continue;
571
572                 if (bio_data_dir(bio) == READ)
573                         pd->iosched.successive_reads += bio->bi_size >> 10;
574                 else {
575                         pd->iosched.successive_reads = 0;
576                         pd->iosched.last_write = bio->bi_sector + bio_sectors(bio);
577                 }
578                 if (pd->iosched.successive_reads >= HI_SPEED_SWITCH) {
579                         if (pd->read_speed == pd->write_speed) {
580                                 pd->read_speed = MAX_SPEED;
581                                 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
582                         }
583                 } else {
584                         if (pd->read_speed != pd->write_speed) {
585                                 pd->read_speed = pd->write_speed;
586                                 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
587                         }
588                 }
589
590                 atomic_inc(&pd->cdrw.pending_bios);
591                 generic_make_request(bio);
592         }
593 }
594
595 /*
596  * Special care is needed if the underlying block device has a small
597  * max_phys_segments value.
598  */
599 static int pkt_set_segment_merging(struct pktcdvd_device *pd, request_queue_t *q)
600 {
601         if ((pd->settings.size << 9) / CD_FRAMESIZE <= q->max_phys_segments) {
602                 /*
603                  * The cdrom device can handle one segment/frame
604                  */
605                 clear_bit(PACKET_MERGE_SEGS, &pd->flags);
606                 return 0;
607         } else if ((pd->settings.size << 9) / PAGE_SIZE <= q->max_phys_segments) {
608                 /*
609                  * We can handle this case at the expense of some extra memory
610                  * copies during write operations
611                  */
612                 set_bit(PACKET_MERGE_SEGS, &pd->flags);
613                 return 0;
614         } else {
615                 printk("pktcdvd: cdrom max_phys_segments too small\n");
616                 return -EIO;
617         }
618 }
619
620 /*
621  * Copy CD_FRAMESIZE bytes from src_bio into a destination page
622  */
623 static void pkt_copy_bio_data(struct bio *src_bio, int seg, int offs, struct page *dst_page, int dst_offs)
624 {
625         unsigned int copy_size = CD_FRAMESIZE;
626
627         while (copy_size > 0) {
628                 struct bio_vec *src_bvl = bio_iovec_idx(src_bio, seg);
629                 void *vfrom = kmap_atomic(src_bvl->bv_page, KM_USER0) +
630                         src_bvl->bv_offset + offs;
631                 void *vto = page_address(dst_page) + dst_offs;
632                 int len = min_t(int, copy_size, src_bvl->bv_len - offs);
633
634                 BUG_ON(len < 0);
635                 memcpy(vto, vfrom, len);
636                 kunmap_atomic(vfrom, KM_USER0);
637
638                 seg++;
639                 offs = 0;
640                 dst_offs += len;
641                 copy_size -= len;
642         }
643 }
644
645 /*
646  * Copy all data for this packet to pkt->pages[], so that
647  * a) The number of required segments for the write bio is minimized, which
648  *    is necessary for some scsi controllers.
649  * b) The data can be used as cache to avoid read requests if we receive a
650  *    new write request for the same zone.
651  */
652 static void pkt_make_local_copy(struct packet_data *pkt, struct page **pages, int *offsets)
653 {
654         int f, p, offs;
655
656         /* Copy all data to pkt->pages[] */
657         p = 0;
658         offs = 0;
659         for (f = 0; f < pkt->frames; f++) {
660                 if (pages[f] != pkt->pages[p]) {
661                         void *vfrom = kmap_atomic(pages[f], KM_USER0) + offsets[f];
662                         void *vto = page_address(pkt->pages[p]) + offs;
663                         memcpy(vto, vfrom, CD_FRAMESIZE);
664                         kunmap_atomic(vfrom, KM_USER0);
665                         pages[f] = pkt->pages[p];
666                         offsets[f] = offs;
667                 } else {
668                         BUG_ON(offsets[f] != offs);
669                 }
670                 offs += CD_FRAMESIZE;
671                 if (offs >= PAGE_SIZE) {
672                         offs = 0;
673                         p++;
674                 }
675         }
676 }
677
678 static int pkt_end_io_read(struct bio *bio, unsigned int bytes_done, int err)
679 {
680         struct packet_data *pkt = bio->bi_private;
681         struct pktcdvd_device *pd = pkt->pd;
682         BUG_ON(!pd);
683
684         if (bio->bi_size)
685                 return 1;
686
687         VPRINTK("pkt_end_io_read: bio=%p sec0=%llx sec=%llx err=%d\n", bio,
688                 (unsigned long long)pkt->sector, (unsigned long long)bio->bi_sector, err);
689
690         if (err)
691                 atomic_inc(&pkt->io_errors);
692         if (atomic_dec_and_test(&pkt->io_wait)) {
693                 atomic_inc(&pkt->run_sm);
694                 wake_up(&pd->wqueue);
695         }
696         pkt_bio_finished(pd);
697
698         return 0;
699 }
700
701 static int pkt_end_io_packet_write(struct bio *bio, unsigned int bytes_done, int err)
702 {
703         struct packet_data *pkt = bio->bi_private;
704         struct pktcdvd_device *pd = pkt->pd;
705         BUG_ON(!pd);
706
707         if (bio->bi_size)
708                 return 1;
709
710         VPRINTK("pkt_end_io_packet_write: id=%d, err=%d\n", pkt->id, err);
711
712         pd->stats.pkt_ended++;
713
714         pkt_bio_finished(pd);
715         atomic_dec(&pkt->io_wait);
716         atomic_inc(&pkt->run_sm);
717         wake_up(&pd->wqueue);
718         return 0;
719 }
720
721 /*
722  * Schedule reads for the holes in a packet
723  */
724 static void pkt_gather_data(struct pktcdvd_device *pd, struct packet_data *pkt)
725 {
726         int frames_read = 0;
727         struct bio *bio;
728         int f;
729         char written[PACKET_MAX_SIZE];
730
731         BUG_ON(!pkt->orig_bios);
732
733         atomic_set(&pkt->io_wait, 0);
734         atomic_set(&pkt->io_errors, 0);
735
736         /*
737          * Figure out which frames we need to read before we can write.
738          */
739         memset(written, 0, sizeof(written));
740         spin_lock(&pkt->lock);
741         for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
742                 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
743                 int num_frames = bio->bi_size / CD_FRAMESIZE;
744                 pd->stats.secs_w += num_frames * (CD_FRAMESIZE >> 9);
745                 BUG_ON(first_frame < 0);
746                 BUG_ON(first_frame + num_frames > pkt->frames);
747                 for (f = first_frame; f < first_frame + num_frames; f++)
748                         written[f] = 1;
749         }
750         spin_unlock(&pkt->lock);
751
752         if (pkt->cache_valid) {
753                 VPRINTK("pkt_gather_data: zone %llx cached\n",
754                         (unsigned long long)pkt->sector);
755                 goto out_account;
756         }
757
758         /*
759          * Schedule reads for missing parts of the packet.
760          */
761         for (f = 0; f < pkt->frames; f++) {
762                 int p, offset;
763                 if (written[f])
764                         continue;
765                 bio = pkt->r_bios[f];
766                 bio_init(bio);
767                 bio->bi_max_vecs = 1;
768                 bio->bi_sector = pkt->sector + f * (CD_FRAMESIZE >> 9);
769                 bio->bi_bdev = pd->bdev;
770                 bio->bi_end_io = pkt_end_io_read;
771                 bio->bi_private = pkt;
772
773                 p = (f * CD_FRAMESIZE) / PAGE_SIZE;
774                 offset = (f * CD_FRAMESIZE) % PAGE_SIZE;
775                 VPRINTK("pkt_gather_data: Adding frame %d, page:%p offs:%d\n",
776                         f, pkt->pages[p], offset);
777                 if (!bio_add_page(bio, pkt->pages[p], CD_FRAMESIZE, offset))
778                         BUG();
779
780                 atomic_inc(&pkt->io_wait);
781                 bio->bi_rw = READ;
782                 pkt_queue_bio(pd, bio);
783                 frames_read++;
784         }
785
786 out_account:
787         VPRINTK("pkt_gather_data: need %d frames for zone %llx\n",
788                 frames_read, (unsigned long long)pkt->sector);
789         pd->stats.pkt_started++;
790         pd->stats.secs_rg += frames_read * (CD_FRAMESIZE >> 9);
791 }
792
793 /*
794  * Find a packet matching zone, or the least recently used packet if
795  * there is no match.
796  */
797 static struct packet_data *pkt_get_packet_data(struct pktcdvd_device *pd, int zone)
798 {
799         struct packet_data *pkt;
800
801         list_for_each_entry(pkt, &pd->cdrw.pkt_free_list, list) {
802                 if (pkt->sector == zone || pkt->list.next == &pd->cdrw.pkt_free_list) {
803                         list_del_init(&pkt->list);
804                         if (pkt->sector != zone)
805                                 pkt->cache_valid = 0;
806                         return pkt;
807                 }
808         }
809         BUG();
810         return NULL;
811 }
812
813 static void pkt_put_packet_data(struct pktcdvd_device *pd, struct packet_data *pkt)
814 {
815         if (pkt->cache_valid) {
816                 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
817         } else {
818                 list_add_tail(&pkt->list, &pd->cdrw.pkt_free_list);
819         }
820 }
821
822 /*
823  * recover a failed write, query for relocation if possible
824  *
825  * returns 1 if recovery is possible, or 0 if not
826  *
827  */
828 static int pkt_start_recovery(struct packet_data *pkt)
829 {
830         /*
831          * FIXME. We need help from the file system to implement
832          * recovery handling.
833          */
834         return 0;
835 #if 0
836         struct request *rq = pkt->rq;
837         struct pktcdvd_device *pd = rq->rq_disk->private_data;
838         struct block_device *pkt_bdev;
839         struct super_block *sb = NULL;
840         unsigned long old_block, new_block;
841         sector_t new_sector;
842
843         pkt_bdev = bdget(kdev_t_to_nr(pd->pkt_dev));
844         if (pkt_bdev) {
845                 sb = get_super(pkt_bdev);
846                 bdput(pkt_bdev);
847         }
848
849         if (!sb)
850                 return 0;
851
852         if (!sb->s_op || !sb->s_op->relocate_blocks)
853                 goto out;
854
855         old_block = pkt->sector / (CD_FRAMESIZE >> 9);
856         if (sb->s_op->relocate_blocks(sb, old_block, &new_block))
857                 goto out;
858
859         new_sector = new_block * (CD_FRAMESIZE >> 9);
860         pkt->sector = new_sector;
861
862         pkt->bio->bi_sector = new_sector;
863         pkt->bio->bi_next = NULL;
864         pkt->bio->bi_flags = 1 << BIO_UPTODATE;
865         pkt->bio->bi_idx = 0;
866
867         BUG_ON(pkt->bio->bi_rw != (1 << BIO_RW));
868         BUG_ON(pkt->bio->bi_vcnt != pkt->frames);
869         BUG_ON(pkt->bio->bi_size != pkt->frames * CD_FRAMESIZE);
870         BUG_ON(pkt->bio->bi_end_io != pkt_end_io_packet_write);
871         BUG_ON(pkt->bio->bi_private != pkt);
872
873         drop_super(sb);
874         return 1;
875
876 out:
877         drop_super(sb);
878         return 0;
879 #endif
880 }
881
882 static inline void pkt_set_state(struct packet_data *pkt, enum packet_data_state state)
883 {
884 #if PACKET_DEBUG > 1
885         static const char *state_name[] = {
886                 "IDLE", "WAITING", "READ_WAIT", "WRITE_WAIT", "RECOVERY", "FINISHED"
887         };
888         enum packet_data_state old_state = pkt->state;
889         VPRINTK("pkt %2d : s=%6llx %s -> %s\n", pkt->id, (unsigned long long)pkt->sector,
890                 state_name[old_state], state_name[state]);
891 #endif
892         pkt->state = state;
893 }
894
895 /*
896  * Scan the work queue to see if we can start a new packet.
897  * returns non-zero if any work was done.
898  */
899 static int pkt_handle_queue(struct pktcdvd_device *pd)
900 {
901         struct packet_data *pkt, *p;
902         struct bio *bio = NULL;
903         sector_t zone = 0; /* Suppress gcc warning */
904         struct pkt_rb_node *node, *first_node;
905         struct rb_node *n;
906
907         VPRINTK("handle_queue\n");
908
909         atomic_set(&pd->scan_queue, 0);
910
911         if (list_empty(&pd->cdrw.pkt_free_list)) {
912                 VPRINTK("handle_queue: no pkt\n");
913                 return 0;
914         }
915
916         /*
917          * Try to find a zone we are not already working on.
918          */
919         spin_lock(&pd->lock);
920         first_node = pkt_rbtree_find(pd, pd->current_sector);
921         if (!first_node) {
922                 n = rb_first(&pd->bio_queue);
923                 if (n)
924                         first_node = rb_entry(n, struct pkt_rb_node, rb_node);
925         }
926         node = first_node;
927         while (node) {
928                 bio = node->bio;
929                 zone = ZONE(bio->bi_sector, pd);
930                 list_for_each_entry(p, &pd->cdrw.pkt_active_list, list) {
931                         if (p->sector == zone) {
932                                 bio = NULL;
933                                 goto try_next_bio;
934                         }
935                 }
936                 break;
937 try_next_bio:
938                 node = pkt_rbtree_next(node);
939                 if (!node) {
940                         n = rb_first(&pd->bio_queue);
941                         if (n)
942                                 node = rb_entry(n, struct pkt_rb_node, rb_node);
943                 }
944                 if (node == first_node)
945                         node = NULL;
946         }
947         spin_unlock(&pd->lock);
948         if (!bio) {
949                 VPRINTK("handle_queue: no bio\n");
950                 return 0;
951         }
952
953         pkt = pkt_get_packet_data(pd, zone);
954
955         pd->current_sector = zone + pd->settings.size;
956         pkt->sector = zone;
957         pkt->frames = pd->settings.size >> 2;
958         pkt->write_size = 0;
959
960         /*
961          * Scan work queue for bios in the same zone and link them
962          * to this packet.
963          */
964         spin_lock(&pd->lock);
965         VPRINTK("pkt_handle_queue: looking for zone %llx\n", (unsigned long long)zone);
966         while ((node = pkt_rbtree_find(pd, zone)) != NULL) {
967                 bio = node->bio;
968                 VPRINTK("pkt_handle_queue: found zone=%llx\n",
969                         (unsigned long long)ZONE(bio->bi_sector, pd));
970                 if (ZONE(bio->bi_sector, pd) != zone)
971                         break;
972                 pkt_rbtree_erase(pd, node);
973                 spin_lock(&pkt->lock);
974                 pkt_add_list_last(bio, &pkt->orig_bios, &pkt->orig_bios_tail);
975                 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
976                 spin_unlock(&pkt->lock);
977         }
978         spin_unlock(&pd->lock);
979
980         pkt->sleep_time = max(PACKET_WAIT_TIME, 1);
981         pkt_set_state(pkt, PACKET_WAITING_STATE);
982         atomic_set(&pkt->run_sm, 1);
983
984         spin_lock(&pd->cdrw.active_list_lock);
985         list_add(&pkt->list, &pd->cdrw.pkt_active_list);
986         spin_unlock(&pd->cdrw.active_list_lock);
987
988         return 1;
989 }
990
991 /*
992  * Assemble a bio to write one packet and queue the bio for processing
993  * by the underlying block device.
994  */
995 static void pkt_start_write(struct pktcdvd_device *pd, struct packet_data *pkt)
996 {
997         struct bio *bio;
998         struct page *pages[PACKET_MAX_SIZE];
999         int offsets[PACKET_MAX_SIZE];
1000         int f;
1001         int frames_write;
1002
1003         for (f = 0; f < pkt->frames; f++) {
1004                 pages[f] = pkt->pages[(f * CD_FRAMESIZE) / PAGE_SIZE];
1005                 offsets[f] = (f * CD_FRAMESIZE) % PAGE_SIZE;
1006         }
1007
1008         /*
1009          * Fill-in pages[] and offsets[] with data from orig_bios.
1010          */
1011         frames_write = 0;
1012         spin_lock(&pkt->lock);
1013         for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
1014                 int segment = bio->bi_idx;
1015                 int src_offs = 0;
1016                 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
1017                 int num_frames = bio->bi_size / CD_FRAMESIZE;
1018                 BUG_ON(first_frame < 0);
1019                 BUG_ON(first_frame + num_frames > pkt->frames);
1020                 for (f = first_frame; f < first_frame + num_frames; f++) {
1021                         struct bio_vec *src_bvl = bio_iovec_idx(bio, segment);
1022
1023                         while (src_offs >= src_bvl->bv_len) {
1024                                 src_offs -= src_bvl->bv_len;
1025                                 segment++;
1026                                 BUG_ON(segment >= bio->bi_vcnt);
1027                                 src_bvl = bio_iovec_idx(bio, segment);
1028                         }
1029
1030                         if (src_bvl->bv_len - src_offs >= CD_FRAMESIZE) {
1031                                 pages[f] = src_bvl->bv_page;
1032                                 offsets[f] = src_bvl->bv_offset + src_offs;
1033                         } else {
1034                                 pkt_copy_bio_data(bio, segment, src_offs,
1035                                                   pages[f], offsets[f]);
1036                         }
1037                         src_offs += CD_FRAMESIZE;
1038                         frames_write++;
1039                 }
1040         }
1041         pkt_set_state(pkt, PACKET_WRITE_WAIT_STATE);
1042         spin_unlock(&pkt->lock);
1043
1044         VPRINTK("pkt_start_write: Writing %d frames for zone %llx\n",
1045                 frames_write, (unsigned long long)pkt->sector);
1046         BUG_ON(frames_write != pkt->write_size);
1047
1048         if (test_bit(PACKET_MERGE_SEGS, &pd->flags) || (pkt->write_size < pkt->frames)) {
1049                 pkt_make_local_copy(pkt, pages, offsets);
1050                 pkt->cache_valid = 1;
1051         } else {
1052                 pkt->cache_valid = 0;
1053         }
1054
1055         /* Start the write request */
1056         bio_init(pkt->w_bio);
1057         pkt->w_bio->bi_max_vecs = PACKET_MAX_SIZE;
1058         pkt->w_bio->bi_sector = pkt->sector;
1059         pkt->w_bio->bi_bdev = pd->bdev;
1060         pkt->w_bio->bi_end_io = pkt_end_io_packet_write;
1061         pkt->w_bio->bi_private = pkt;
1062         for (f = 0; f < pkt->frames; f++) {
1063                 if ((f + 1 < pkt->frames) && (pages[f + 1] == pages[f]) &&
1064                     (offsets[f + 1] = offsets[f] + CD_FRAMESIZE)) {
1065                         if (!bio_add_page(pkt->w_bio, pages[f], CD_FRAMESIZE * 2, offsets[f]))
1066                                 BUG();
1067                         f++;
1068                 } else {
1069                         if (!bio_add_page(pkt->w_bio, pages[f], CD_FRAMESIZE, offsets[f]))
1070                                 BUG();
1071                 }
1072         }
1073         VPRINTK("pktcdvd: vcnt=%d\n", pkt->w_bio->bi_vcnt);
1074
1075         atomic_set(&pkt->io_wait, 1);
1076         pkt->w_bio->bi_rw = WRITE;
1077         pkt_queue_bio(pd, pkt->w_bio);
1078 }
1079
1080 static void pkt_finish_packet(struct packet_data *pkt, int uptodate)
1081 {
1082         struct bio *bio, *next;
1083
1084         if (!uptodate)
1085                 pkt->cache_valid = 0;
1086
1087         /* Finish all bios corresponding to this packet */
1088         bio = pkt->orig_bios;
1089         while (bio) {
1090                 next = bio->bi_next;
1091                 bio->bi_next = NULL;
1092                 bio_endio(bio, bio->bi_size, uptodate ? 0 : -EIO);
1093                 bio = next;
1094         }
1095         pkt->orig_bios = pkt->orig_bios_tail = NULL;
1096 }
1097
1098 static void pkt_run_state_machine(struct pktcdvd_device *pd, struct packet_data *pkt)
1099 {
1100         int uptodate;
1101
1102         VPRINTK("run_state_machine: pkt %d\n", pkt->id);
1103
1104         for (;;) {
1105                 switch (pkt->state) {
1106                 case PACKET_WAITING_STATE:
1107                         if ((pkt->write_size < pkt->frames) && (pkt->sleep_time > 0))
1108                                 return;
1109
1110                         pkt->sleep_time = 0;
1111                         pkt_gather_data(pd, pkt);
1112                         pkt_set_state(pkt, PACKET_READ_WAIT_STATE);
1113                         break;
1114
1115                 case PACKET_READ_WAIT_STATE:
1116                         if (atomic_read(&pkt->io_wait) > 0)
1117                                 return;
1118
1119                         if (atomic_read(&pkt->io_errors) > 0) {
1120                                 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1121                         } else {
1122                                 pkt_start_write(pd, pkt);
1123                         }
1124                         break;
1125
1126                 case PACKET_WRITE_WAIT_STATE:
1127                         if (atomic_read(&pkt->io_wait) > 0)
1128                                 return;
1129
1130                         if (test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags)) {
1131                                 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1132                         } else {
1133                                 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1134                         }
1135                         break;
1136
1137                 case PACKET_RECOVERY_STATE:
1138                         if (pkt_start_recovery(pkt)) {
1139                                 pkt_start_write(pd, pkt);
1140                         } else {
1141                                 VPRINTK("No recovery possible\n");
1142                                 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1143                         }
1144                         break;
1145
1146                 case PACKET_FINISHED_STATE:
1147                         uptodate = test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags);
1148                         pkt_finish_packet(pkt, uptodate);
1149                         return;
1150
1151                 default:
1152                         BUG();
1153                         break;
1154                 }
1155         }
1156 }
1157
1158 static void pkt_handle_packets(struct pktcdvd_device *pd)
1159 {
1160         struct packet_data *pkt, *next;
1161
1162         VPRINTK("pkt_handle_packets\n");
1163
1164         /*
1165          * Run state machine for active packets
1166          */
1167         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1168                 if (atomic_read(&pkt->run_sm) > 0) {
1169                         atomic_set(&pkt->run_sm, 0);
1170                         pkt_run_state_machine(pd, pkt);
1171                 }
1172         }
1173
1174         /*
1175          * Move no longer active packets to the free list
1176          */
1177         spin_lock(&pd->cdrw.active_list_lock);
1178         list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_active_list, list) {
1179                 if (pkt->state == PACKET_FINISHED_STATE) {
1180                         list_del(&pkt->list);
1181                         pkt_put_packet_data(pd, pkt);
1182                         pkt_set_state(pkt, PACKET_IDLE_STATE);
1183                         atomic_set(&pd->scan_queue, 1);
1184                 }
1185         }
1186         spin_unlock(&pd->cdrw.active_list_lock);
1187 }
1188
1189 static void pkt_count_states(struct pktcdvd_device *pd, int *states)
1190 {
1191         struct packet_data *pkt;
1192         int i;
1193
1194         for (i = 0; i <= PACKET_NUM_STATES; i++)
1195                 states[i] = 0;
1196
1197         spin_lock(&pd->cdrw.active_list_lock);
1198         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1199                 states[pkt->state]++;
1200         }
1201         spin_unlock(&pd->cdrw.active_list_lock);
1202 }
1203
1204 /*
1205  * kcdrwd is woken up when writes have been queued for one of our
1206  * registered devices
1207  */
1208 static int kcdrwd(void *foobar)
1209 {
1210         struct pktcdvd_device *pd = foobar;
1211         struct packet_data *pkt;
1212         long min_sleep_time, residue;
1213
1214         set_user_nice(current, -20);
1215
1216         for (;;) {
1217                 DECLARE_WAITQUEUE(wait, current);
1218
1219                 /*
1220                  * Wait until there is something to do
1221                  */
1222                 add_wait_queue(&pd->wqueue, &wait);
1223                 for (;;) {
1224                         set_current_state(TASK_INTERRUPTIBLE);
1225
1226                         /* Check if we need to run pkt_handle_queue */
1227                         if (atomic_read(&pd->scan_queue) > 0)
1228                                 goto work_to_do;
1229
1230                         /* Check if we need to run the state machine for some packet */
1231                         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1232                                 if (atomic_read(&pkt->run_sm) > 0)
1233                                         goto work_to_do;
1234                         }
1235
1236                         /* Check if we need to process the iosched queues */
1237                         if (atomic_read(&pd->iosched.attention) != 0)
1238                                 goto work_to_do;
1239
1240                         /* Otherwise, go to sleep */
1241                         if (PACKET_DEBUG > 1) {
1242                                 int states[PACKET_NUM_STATES];
1243                                 pkt_count_states(pd, states);
1244                                 VPRINTK("kcdrwd: i:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
1245                                         states[0], states[1], states[2], states[3],
1246                                         states[4], states[5]);
1247                         }
1248
1249                         min_sleep_time = MAX_SCHEDULE_TIMEOUT;
1250                         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1251                                 if (pkt->sleep_time && pkt->sleep_time < min_sleep_time)
1252                                         min_sleep_time = pkt->sleep_time;
1253                         }
1254
1255                         generic_unplug_device(bdev_get_queue(pd->bdev));
1256
1257                         VPRINTK("kcdrwd: sleeping\n");
1258                         residue = schedule_timeout(min_sleep_time);
1259                         VPRINTK("kcdrwd: wake up\n");
1260
1261                         /* make swsusp happy with our thread */
1262                         try_to_freeze();
1263
1264                         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1265                                 if (!pkt->sleep_time)
1266                                         continue;
1267                                 pkt->sleep_time -= min_sleep_time - residue;
1268                                 if (pkt->sleep_time <= 0) {
1269                                         pkt->sleep_time = 0;
1270                                         atomic_inc(&pkt->run_sm);
1271                                 }
1272                         }
1273
1274                         if (signal_pending(current)) {
1275                                 flush_signals(current);
1276                         }
1277                         if (kthread_should_stop())
1278                                 break;
1279                 }
1280 work_to_do:
1281                 set_current_state(TASK_RUNNING);
1282                 remove_wait_queue(&pd->wqueue, &wait);
1283
1284                 if (kthread_should_stop())
1285                         break;
1286
1287                 /*
1288                  * if pkt_handle_queue returns true, we can queue
1289                  * another request.
1290                  */
1291                 while (pkt_handle_queue(pd))
1292                         ;
1293
1294                 /*
1295                  * Handle packet state machine
1296                  */
1297                 pkt_handle_packets(pd);
1298
1299                 /*
1300                  * Handle iosched queues
1301                  */
1302                 pkt_iosched_process_queue(pd);
1303         }
1304
1305         return 0;
1306 }
1307
1308 static void pkt_print_settings(struct pktcdvd_device *pd)
1309 {
1310         printk("pktcdvd: %s packets, ", pd->settings.fp ? "Fixed" : "Variable");
1311         printk("%u blocks, ", pd->settings.size >> 2);
1312         printk("Mode-%c disc\n", pd->settings.block_mode == 8 ? '1' : '2');
1313 }
1314
1315 static int pkt_mode_sense(struct pktcdvd_device *pd, struct packet_command *cgc, int page_code, int page_control)
1316 {
1317         memset(cgc->cmd, 0, sizeof(cgc->cmd));
1318
1319         cgc->cmd[0] = GPCMD_MODE_SENSE_10;
1320         cgc->cmd[2] = page_code | (page_control << 6);
1321         cgc->cmd[7] = cgc->buflen >> 8;
1322         cgc->cmd[8] = cgc->buflen & 0xff;
1323         cgc->data_direction = CGC_DATA_READ;
1324         return pkt_generic_packet(pd, cgc);
1325 }
1326
1327 static int pkt_mode_select(struct pktcdvd_device *pd, struct packet_command *cgc)
1328 {
1329         memset(cgc->cmd, 0, sizeof(cgc->cmd));
1330         memset(cgc->buffer, 0, 2);
1331         cgc->cmd[0] = GPCMD_MODE_SELECT_10;
1332         cgc->cmd[1] = 0x10;             /* PF */
1333         cgc->cmd[7] = cgc->buflen >> 8;
1334         cgc->cmd[8] = cgc->buflen & 0xff;
1335         cgc->data_direction = CGC_DATA_WRITE;
1336         return pkt_generic_packet(pd, cgc);
1337 }
1338
1339 static int pkt_get_disc_info(struct pktcdvd_device *pd, disc_information *di)
1340 {
1341         struct packet_command cgc;
1342         int ret;
1343
1344         /* set up command and get the disc info */
1345         init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);
1346         cgc.cmd[0] = GPCMD_READ_DISC_INFO;
1347         cgc.cmd[8] = cgc.buflen = 2;
1348         cgc.quiet = 1;
1349
1350         if ((ret = pkt_generic_packet(pd, &cgc)))
1351                 return ret;
1352
1353         /* not all drives have the same disc_info length, so requeue
1354          * packet with the length the drive tells us it can supply
1355          */
1356         cgc.buflen = be16_to_cpu(di->disc_information_length) +
1357                      sizeof(di->disc_information_length);
1358
1359         if (cgc.buflen > sizeof(disc_information))
1360                 cgc.buflen = sizeof(disc_information);
1361
1362         cgc.cmd[8] = cgc.buflen;
1363         return pkt_generic_packet(pd, &cgc);
1364 }
1365
1366 static int pkt_get_track_info(struct pktcdvd_device *pd, __u16 track, __u8 type, track_information *ti)
1367 {
1368         struct packet_command cgc;
1369         int ret;
1370
1371         init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);
1372         cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;
1373         cgc.cmd[1] = type & 3;
1374         cgc.cmd[4] = (track & 0xff00) >> 8;
1375         cgc.cmd[5] = track & 0xff;
1376         cgc.cmd[8] = 8;
1377         cgc.quiet = 1;
1378
1379         if ((ret = pkt_generic_packet(pd, &cgc)))
1380                 return ret;
1381
1382         cgc.buflen = be16_to_cpu(ti->track_information_length) +
1383                      sizeof(ti->track_information_length);
1384
1385         if (cgc.buflen > sizeof(track_information))
1386                 cgc.buflen = sizeof(track_information);
1387
1388         cgc.cmd[8] = cgc.buflen;
1389         return pkt_generic_packet(pd, &cgc);
1390 }
1391
1392 static int pkt_get_last_written(struct pktcdvd_device *pd, long *last_written)
1393 {
1394         disc_information di;
1395         track_information ti;
1396         __u32 last_track;
1397         int ret = -1;
1398
1399         if ((ret = pkt_get_disc_info(pd, &di)))
1400                 return ret;
1401
1402         last_track = (di.last_track_msb << 8) | di.last_track_lsb;
1403         if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1404                 return ret;
1405
1406         /* if this track is blank, try the previous. */
1407         if (ti.blank) {
1408                 last_track--;
1409                 if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1410                         return ret;
1411         }
1412
1413         /* if last recorded field is valid, return it. */
1414         if (ti.lra_v) {
1415                 *last_written = be32_to_cpu(ti.last_rec_address);
1416         } else {
1417                 /* make it up instead */
1418                 *last_written = be32_to_cpu(ti.track_start) +
1419                                 be32_to_cpu(ti.track_size);
1420                 if (ti.free_blocks)
1421                         *last_written -= (be32_to_cpu(ti.free_blocks) + 7);
1422         }
1423         return 0;
1424 }
1425
1426 /*
1427  * write mode select package based on pd->settings
1428  */
1429 static int pkt_set_write_settings(struct pktcdvd_device *pd)
1430 {
1431         struct packet_command cgc;
1432         struct request_sense sense;
1433         write_param_page *wp;
1434         char buffer[128];
1435         int ret, size;
1436
1437         /* doesn't apply to DVD+RW or DVD-RAM */
1438         if ((pd->mmc3_profile == 0x1a) || (pd->mmc3_profile == 0x12))
1439                 return 0;
1440
1441         memset(buffer, 0, sizeof(buffer));
1442         init_cdrom_command(&cgc, buffer, sizeof(*wp), CGC_DATA_READ);
1443         cgc.sense = &sense;
1444         if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1445                 pkt_dump_sense(&cgc);
1446                 return ret;
1447         }
1448
1449         size = 2 + ((buffer[0] << 8) | (buffer[1] & 0xff));
1450         pd->mode_offset = (buffer[6] << 8) | (buffer[7] & 0xff);
1451         if (size > sizeof(buffer))
1452                 size = sizeof(buffer);
1453
1454         /*
1455          * now get it all
1456          */
1457         init_cdrom_command(&cgc, buffer, size, CGC_DATA_READ);
1458         cgc.sense = &sense;
1459         if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1460                 pkt_dump_sense(&cgc);
1461                 return ret;
1462         }
1463
1464         /*
1465          * write page is offset header + block descriptor length
1466          */
1467         wp = (write_param_page *) &buffer[sizeof(struct mode_page_header) + pd->mode_offset];
1468
1469         wp->fp = pd->settings.fp;
1470         wp->track_mode = pd->settings.track_mode;
1471         wp->write_type = pd->settings.write_type;
1472         wp->data_block_type = pd->settings.block_mode;
1473
1474         wp->multi_session = 0;
1475
1476 #ifdef PACKET_USE_LS
1477         wp->link_size = 7;
1478         wp->ls_v = 1;
1479 #endif
1480
1481         if (wp->data_block_type == PACKET_BLOCK_MODE1) {
1482                 wp->session_format = 0;
1483                 wp->subhdr2 = 0x20;
1484         } else if (wp->data_block_type == PACKET_BLOCK_MODE2) {
1485                 wp->session_format = 0x20;
1486                 wp->subhdr2 = 8;
1487 #if 0
1488                 wp->mcn[0] = 0x80;
1489                 memcpy(&wp->mcn[1], PACKET_MCN, sizeof(wp->mcn) - 1);
1490 #endif
1491         } else {
1492                 /*
1493                  * paranoia
1494                  */
1495                 printk("pktcdvd: write mode wrong %d\n", wp->data_block_type);
1496                 return 1;
1497         }
1498         wp->packet_size = cpu_to_be32(pd->settings.size >> 2);
1499
1500         cgc.buflen = cgc.cmd[8] = size;
1501         if ((ret = pkt_mode_select(pd, &cgc))) {
1502                 pkt_dump_sense(&cgc);
1503                 return ret;
1504         }
1505
1506         pkt_print_settings(pd);
1507         return 0;
1508 }
1509
1510 /*
1511  * 0 -- we can write to this track, 1 -- we can't
1512  */
1513 static int pkt_good_track(track_information *ti)
1514 {
1515         /*
1516          * only good for CD-RW at the moment, not DVD-RW
1517          */
1518
1519         /*
1520          * FIXME: only for FP
1521          */
1522         if (ti->fp == 0)
1523                 return 0;
1524
1525         /*
1526          * "good" settings as per Mt Fuji.
1527          */
1528         if (ti->rt == 0 && ti->blank == 0 && ti->packet == 1)
1529                 return 0;
1530
1531         if (ti->rt == 0 && ti->blank == 1 && ti->packet == 1)
1532                 return 0;
1533
1534         if (ti->rt == 1 && ti->blank == 0 && ti->packet == 1)
1535                 return 0;
1536
1537         printk("pktcdvd: bad state %d-%d-%d\n", ti->rt, ti->blank, ti->packet);
1538         return 1;
1539 }
1540
1541 /*
1542  * 0 -- we can write to this disc, 1 -- we can't
1543  */
1544 static int pkt_good_disc(struct pktcdvd_device *pd, disc_information *di)
1545 {
1546         switch (pd->mmc3_profile) {
1547                 case 0x0a: /* CD-RW */
1548                 case 0xffff: /* MMC3 not supported */
1549                         break;
1550                 case 0x1a: /* DVD+RW */
1551                 case 0x13: /* DVD-RW */
1552                 case 0x12: /* DVD-RAM */
1553                         return 0;
1554                 default:
1555                         printk("pktcdvd: Wrong disc profile (%x)\n", pd->mmc3_profile);
1556                         return 1;
1557         }
1558
1559         /*
1560          * for disc type 0xff we should probably reserve a new track.
1561          * but i'm not sure, should we leave this to user apps? probably.
1562          */
1563         if (di->disc_type == 0xff) {
1564                 printk("pktcdvd: Unknown disc. No track?\n");
1565                 return 1;
1566         }
1567
1568         if (di->disc_type != 0x20 && di->disc_type != 0) {
1569                 printk("pktcdvd: Wrong disc type (%x)\n", di->disc_type);
1570                 return 1;
1571         }
1572
1573         if (di->erasable == 0) {
1574                 printk("pktcdvd: Disc not erasable\n");
1575                 return 1;
1576         }
1577
1578         if (di->border_status == PACKET_SESSION_RESERVED) {
1579                 printk("pktcdvd: Can't write to last track (reserved)\n");
1580                 return 1;
1581         }
1582
1583         return 0;
1584 }
1585
1586 static int pkt_probe_settings(struct pktcdvd_device *pd)
1587 {
1588         struct packet_command cgc;
1589         unsigned char buf[12];
1590         disc_information di;
1591         track_information ti;
1592         int ret, track;
1593
1594         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1595         cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
1596         cgc.cmd[8] = 8;
1597         ret = pkt_generic_packet(pd, &cgc);
1598         pd->mmc3_profile = ret ? 0xffff : buf[6] << 8 | buf[7];
1599
1600         memset(&di, 0, sizeof(disc_information));
1601         memset(&ti, 0, sizeof(track_information));
1602
1603         if ((ret = pkt_get_disc_info(pd, &di))) {
1604                 printk("failed get_disc\n");
1605                 return ret;
1606         }
1607
1608         if (pkt_good_disc(pd, &di))
1609                 return -ENXIO;
1610
1611         switch (pd->mmc3_profile) {
1612                 case 0x1a: /* DVD+RW */
1613                         printk("pktcdvd: inserted media is DVD+RW\n");
1614                         break;
1615                 case 0x13: /* DVD-RW */
1616                         printk("pktcdvd: inserted media is DVD-RW\n");
1617                         break;
1618                 case 0x12: /* DVD-RAM */
1619                         printk("pktcdvd: inserted media is DVD-RAM\n");
1620                         break;
1621                 default:
1622                         printk("pktcdvd: inserted media is CD-R%s\n", di.erasable ? "W" : "");
1623                         break;
1624         }
1625         pd->type = di.erasable ? PACKET_CDRW : PACKET_CDR;
1626
1627         track = 1; /* (di.last_track_msb << 8) | di.last_track_lsb; */
1628         if ((ret = pkt_get_track_info(pd, track, 1, &ti))) {
1629                 printk("pktcdvd: failed get_track\n");
1630                 return ret;
1631         }
1632
1633         if (pkt_good_track(&ti)) {
1634                 printk("pktcdvd: can't write to this track\n");
1635                 return -ENXIO;
1636         }
1637
1638         /*
1639          * we keep packet size in 512 byte units, makes it easier to
1640          * deal with request calculations.
1641          */
1642         pd->settings.size = be32_to_cpu(ti.fixed_packet_size) << 2;
1643         if (pd->settings.size == 0) {
1644                 printk("pktcdvd: detected zero packet size!\n");
1645                 pd->settings.size = 128;
1646         }
1647         if (pd->settings.size > PACKET_MAX_SECTORS) {
1648                 printk("pktcdvd: packet size is too big\n");
1649                 return -ENXIO;
1650         }
1651         pd->settings.fp = ti.fp;
1652         pd->offset = (be32_to_cpu(ti.track_start) << 2) & (pd->settings.size - 1);
1653
1654         if (ti.nwa_v) {
1655                 pd->nwa = be32_to_cpu(ti.next_writable);
1656                 set_bit(PACKET_NWA_VALID, &pd->flags);
1657         }
1658
1659         /*
1660          * in theory we could use lra on -RW media as well and just zero
1661          * blocks that haven't been written yet, but in practice that
1662          * is just a no-go. we'll use that for -R, naturally.
1663          */
1664         if (ti.lra_v) {
1665                 pd->lra = be32_to_cpu(ti.last_rec_address);
1666                 set_bit(PACKET_LRA_VALID, &pd->flags);
1667         } else {
1668                 pd->lra = 0xffffffff;
1669                 set_bit(PACKET_LRA_VALID, &pd->flags);
1670         }
1671
1672         /*
1673          * fine for now
1674          */
1675         pd->settings.link_loss = 7;
1676         pd->settings.write_type = 0;    /* packet */
1677         pd->settings.track_mode = ti.track_mode;
1678
1679         /*
1680          * mode1 or mode2 disc
1681          */
1682         switch (ti.data_mode) {
1683                 case PACKET_MODE1:
1684                         pd->settings.block_mode = PACKET_BLOCK_MODE1;
1685                         break;
1686                 case PACKET_MODE2:
1687                         pd->settings.block_mode = PACKET_BLOCK_MODE2;
1688                         break;
1689                 default:
1690                         printk("pktcdvd: unknown data mode\n");
1691                         return 1;
1692         }
1693         return 0;
1694 }
1695
1696 /*
1697  * enable/disable write caching on drive
1698  */
1699 static int pkt_write_caching(struct pktcdvd_device *pd, int set)
1700 {
1701         struct packet_command cgc;
1702         struct request_sense sense;
1703         unsigned char buf[64];
1704         int ret;
1705
1706         memset(buf, 0, sizeof(buf));
1707         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1708         cgc.sense = &sense;
1709         cgc.buflen = pd->mode_offset + 12;
1710
1711         /*
1712          * caching mode page might not be there, so quiet this command
1713          */
1714         cgc.quiet = 1;
1715
1716         if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WCACHING_PAGE, 0)))
1717                 return ret;
1718
1719         buf[pd->mode_offset + 10] |= (!!set << 2);
1720
1721         cgc.buflen = cgc.cmd[8] = 2 + ((buf[0] << 8) | (buf[1] & 0xff));
1722         ret = pkt_mode_select(pd, &cgc);
1723         if (ret) {
1724                 printk("pktcdvd: write caching control failed\n");
1725                 pkt_dump_sense(&cgc);
1726         } else if (!ret && set)
1727                 printk("pktcdvd: enabled write caching on %s\n", pd->name);
1728         return ret;
1729 }
1730
1731 static int pkt_lock_door(struct pktcdvd_device *pd, int lockflag)
1732 {
1733         struct packet_command cgc;
1734
1735         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
1736         cgc.cmd[0] = GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL;
1737         cgc.cmd[4] = lockflag ? 1 : 0;
1738         return pkt_generic_packet(pd, &cgc);
1739 }
1740
1741 /*
1742  * Returns drive maximum write speed
1743  */
1744 static int pkt_get_max_speed(struct pktcdvd_device *pd, unsigned *write_speed)
1745 {
1746         struct packet_command cgc;
1747         struct request_sense sense;
1748         unsigned char buf[256+18];
1749         unsigned char *cap_buf;
1750         int ret, offset;
1751
1752         memset(buf, 0, sizeof(buf));
1753         cap_buf = &buf[sizeof(struct mode_page_header) + pd->mode_offset];
1754         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_UNKNOWN);
1755         cgc.sense = &sense;
1756
1757         ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
1758         if (ret) {
1759                 cgc.buflen = pd->mode_offset + cap_buf[1] + 2 +
1760                              sizeof(struct mode_page_header);
1761                 ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
1762                 if (ret) {
1763                         pkt_dump_sense(&cgc);
1764                         return ret;
1765                 }
1766         }
1767
1768         offset = 20;                        /* Obsoleted field, used by older drives */
1769         if (cap_buf[1] >= 28)
1770                 offset = 28;                /* Current write speed selected */
1771         if (cap_buf[1] >= 30) {
1772                 /* If the drive reports at least one "Logical Unit Write
1773                  * Speed Performance Descriptor Block", use the information
1774                  * in the first block. (contains the highest speed)
1775                  */
1776                 int num_spdb = (cap_buf[30] << 8) + cap_buf[31];
1777                 if (num_spdb > 0)
1778                         offset = 34;
1779         }
1780
1781         *write_speed = (cap_buf[offset] << 8) | cap_buf[offset + 1];
1782         return 0;
1783 }
1784
1785 /* These tables from cdrecord - I don't have orange book */
1786 /* standard speed CD-RW (1-4x) */
1787 static char clv_to_speed[16] = {
1788         /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 */
1789            0, 2, 4, 6, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1790 };
1791 /* high speed CD-RW (-10x) */
1792 static char hs_clv_to_speed[16] = {
1793         /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 */
1794            0, 2, 4, 6, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1795 };
1796 /* ultra high speed CD-RW */
1797 static char us_clv_to_speed[16] = {
1798         /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 */
1799            0, 2, 4, 8, 0, 0,16, 0,24,32,40,48, 0, 0, 0, 0
1800 };
1801
1802 /*
1803  * reads the maximum media speed from ATIP
1804  */
1805 static int pkt_media_speed(struct pktcdvd_device *pd, unsigned *speed)
1806 {
1807         struct packet_command cgc;
1808         struct request_sense sense;
1809         unsigned char buf[64];
1810         unsigned int size, st, sp;
1811         int ret;
1812
1813         init_cdrom_command(&cgc, buf, 2, CGC_DATA_READ);
1814         cgc.sense = &sense;
1815         cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
1816         cgc.cmd[1] = 2;
1817         cgc.cmd[2] = 4; /* READ ATIP */
1818         cgc.cmd[8] = 2;
1819         ret = pkt_generic_packet(pd, &cgc);
1820         if (ret) {
1821                 pkt_dump_sense(&cgc);
1822                 return ret;
1823         }
1824         size = ((unsigned int) buf[0]<<8) + buf[1] + 2;
1825         if (size > sizeof(buf))
1826                 size = sizeof(buf);
1827
1828         init_cdrom_command(&cgc, buf, size, CGC_DATA_READ);
1829         cgc.sense = &sense;
1830         cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
1831         cgc.cmd[1] = 2;
1832         cgc.cmd[2] = 4;
1833         cgc.cmd[8] = size;
1834         ret = pkt_generic_packet(pd, &cgc);
1835         if (ret) {
1836                 pkt_dump_sense(&cgc);
1837                 return ret;
1838         }
1839
1840         if (!buf[6] & 0x40) {
1841                 printk("pktcdvd: Disc type is not CD-RW\n");
1842                 return 1;
1843         }
1844         if (!buf[6] & 0x4) {
1845                 printk("pktcdvd: A1 values on media are not valid, maybe not CDRW?\n");
1846                 return 1;
1847         }
1848
1849         st = (buf[6] >> 3) & 0x7; /* disc sub-type */
1850
1851         sp = buf[16] & 0xf; /* max speed from ATIP A1 field */
1852
1853         /* Info from cdrecord */
1854         switch (st) {
1855                 case 0: /* standard speed */
1856                         *speed = clv_to_speed[sp];
1857                         break;
1858                 case 1: /* high speed */
1859                         *speed = hs_clv_to_speed[sp];
1860                         break;
1861                 case 2: /* ultra high speed */
1862                         *speed = us_clv_to_speed[sp];
1863                         break;
1864                 default:
1865                         printk("pktcdvd: Unknown disc sub-type %d\n",st);
1866                         return 1;
1867         }
1868         if (*speed) {
1869                 printk("pktcdvd: Max. media speed: %d\n",*speed);
1870                 return 0;
1871         } else {
1872                 printk("pktcdvd: Unknown speed %d for sub-type %d\n",sp,st);
1873                 return 1;
1874         }
1875 }
1876
1877 static int pkt_perform_opc(struct pktcdvd_device *pd)
1878 {
1879         struct packet_command cgc;
1880         struct request_sense sense;
1881         int ret;
1882
1883         VPRINTK("pktcdvd: Performing OPC\n");
1884
1885         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
1886         cgc.sense = &sense;
1887         cgc.timeout = 60*HZ;
1888         cgc.cmd[0] = GPCMD_SEND_OPC;
1889         cgc.cmd[1] = 1;
1890         if ((ret = pkt_generic_packet(pd, &cgc)))
1891                 pkt_dump_sense(&cgc);
1892         return ret;
1893 }
1894
1895 static int pkt_open_write(struct pktcdvd_device *pd)
1896 {
1897         int ret;
1898         unsigned int write_speed, media_write_speed, read_speed;
1899
1900         if ((ret = pkt_probe_settings(pd))) {
1901                 DPRINTK("pktcdvd: %s failed probe\n", pd->name);
1902                 return -EIO;
1903         }
1904
1905         if ((ret = pkt_set_write_settings(pd))) {
1906                 DPRINTK("pktcdvd: %s failed saving write settings\n", pd->name);
1907                 return -EIO;
1908         }
1909
1910         pkt_write_caching(pd, USE_WCACHING);
1911
1912         if ((ret = pkt_get_max_speed(pd, &write_speed)))
1913                 write_speed = 16 * 177;
1914         switch (pd->mmc3_profile) {
1915                 case 0x13: /* DVD-RW */
1916                 case 0x1a: /* DVD+RW */
1917                 case 0x12: /* DVD-RAM */
1918                         DPRINTK("pktcdvd: write speed %ukB/s\n", write_speed);
1919                         break;
1920                 default:
1921                         if ((ret = pkt_media_speed(pd, &media_write_speed)))
1922                                 media_write_speed = 16;
1923                         write_speed = min(write_speed, media_write_speed * 177);
1924                         DPRINTK("pktcdvd: write speed %ux\n", write_speed / 176);
1925                         break;
1926         }
1927         read_speed = write_speed;
1928
1929         if ((ret = pkt_set_speed(pd, write_speed, read_speed))) {
1930                 DPRINTK("pktcdvd: %s couldn't set write speed\n", pd->name);
1931                 return -EIO;
1932         }
1933         pd->write_speed = write_speed;
1934         pd->read_speed = read_speed;
1935
1936         if ((ret = pkt_perform_opc(pd))) {
1937                 DPRINTK("pktcdvd: %s Optimum Power Calibration failed\n", pd->name);
1938         }
1939
1940         return 0;
1941 }
1942
1943 /*
1944  * called at open time.
1945  */
1946 static int pkt_open_dev(struct pktcdvd_device *pd, int write)
1947 {
1948         int ret;
1949         long lba;
1950         request_queue_t *q;
1951
1952         /*
1953          * We need to re-open the cdrom device without O_NONBLOCK to be able
1954          * to read/write from/to it. It is already opened in O_NONBLOCK mode
1955          * so bdget() can't fail.
1956          */
1957         bdget(pd->bdev->bd_dev);
1958         if ((ret = blkdev_get(pd->bdev, FMODE_READ, O_RDONLY)))
1959                 goto out;
1960
1961         if ((ret = pkt_get_last_written(pd, &lba))) {
1962                 printk("pktcdvd: pkt_get_last_written failed\n");
1963                 goto out_putdev;
1964         }
1965
1966         set_capacity(pd->disk, lba << 2);
1967         set_capacity(pd->bdev->bd_disk, lba << 2);
1968         bd_set_size(pd->bdev, (loff_t)lba << 11);
1969
1970         q = bdev_get_queue(pd->bdev);
1971         if (write) {
1972                 if ((ret = pkt_open_write(pd)))
1973                         goto out_putdev;
1974                 /*
1975                  * Some CDRW drives can not handle writes larger than one packet,
1976                  * even if the size is a multiple of the packet size.
1977                  */
1978                 spin_lock_irq(q->queue_lock);
1979                 blk_queue_max_sectors(q, pd->settings.size);
1980                 spin_unlock_irq(q->queue_lock);
1981                 set_bit(PACKET_WRITABLE, &pd->flags);
1982         } else {
1983                 pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
1984                 clear_bit(PACKET_WRITABLE, &pd->flags);
1985         }
1986
1987         if ((ret = pkt_set_segment_merging(pd, q)))
1988                 goto out_putdev;
1989
1990         if (write)
1991                 printk("pktcdvd: %lukB available on disc\n", lba << 1);
1992
1993         return 0;
1994
1995 out_putdev:
1996         blkdev_put(pd->bdev);
1997 out:
1998         return ret;
1999 }
2000
2001 /*
2002  * called when the device is closed. makes sure that the device flushes
2003  * the internal cache before we close.
2004  */
2005 static void pkt_release_dev(struct pktcdvd_device *pd, int flush)
2006 {
2007         if (flush && pkt_flush_cache(pd))
2008                 DPRINTK("pktcdvd: %s not flushing cache\n", pd->name);
2009
2010         pkt_lock_door(pd, 0);
2011
2012         pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
2013         blkdev_put(pd->bdev);
2014 }
2015
2016 static struct pktcdvd_device *pkt_find_dev_from_minor(int dev_minor)
2017 {
2018         if (dev_minor >= MAX_WRITERS)
2019                 return NULL;
2020         return pkt_devs[dev_minor];
2021 }
2022
2023 static int pkt_open(struct inode *inode, struct file *file)
2024 {
2025         struct pktcdvd_device *pd = NULL;
2026         int ret;
2027
2028         VPRINTK("pktcdvd: entering open\n");
2029
2030         down(&ctl_mutex);
2031         pd = pkt_find_dev_from_minor(iminor(inode));
2032         if (!pd) {
2033                 ret = -ENODEV;
2034                 goto out;
2035         }
2036         BUG_ON(pd->refcnt < 0);
2037
2038         pd->refcnt++;
2039         if (pd->refcnt > 1) {
2040                 if ((file->f_mode & FMODE_WRITE) &&
2041                     !test_bit(PACKET_WRITABLE, &pd->flags)) {
2042                         ret = -EBUSY;
2043                         goto out_dec;
2044                 }
2045         } else {
2046                 if (pkt_open_dev(pd, file->f_mode & FMODE_WRITE)) {
2047                         ret = -EIO;
2048                         goto out_dec;
2049                 }
2050                 /*
2051                  * needed here as well, since ext2 (among others) may change
2052                  * the blocksize at mount time
2053                  */
2054                 set_blocksize(inode->i_bdev, CD_FRAMESIZE);
2055         }
2056
2057         up(&ctl_mutex);
2058         return 0;
2059
2060 out_dec:
2061         pd->refcnt--;
2062 out:
2063         VPRINTK("pktcdvd: failed open (%d)\n", ret);
2064         up(&ctl_mutex);
2065         return ret;
2066 }
2067
2068 static int pkt_close(struct inode *inode, struct file *file)
2069 {
2070         struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2071         int ret = 0;
2072
2073         down(&ctl_mutex);
2074         pd->refcnt--;
2075         BUG_ON(pd->refcnt < 0);
2076         if (pd->refcnt == 0) {
2077                 int flush = test_bit(PACKET_WRITABLE, &pd->flags);
2078                 pkt_release_dev(pd, flush);
2079         }
2080         up(&ctl_mutex);
2081         return ret;
2082 }
2083
2084
2085 static void *psd_pool_alloc(gfp_t gfp_mask, void *data)
2086 {
2087         return kmalloc(sizeof(struct packet_stacked_data), gfp_mask);
2088 }
2089
2090 static void psd_pool_free(void *ptr, void *data)
2091 {
2092         kfree(ptr);
2093 }
2094
2095 static int pkt_end_io_read_cloned(struct bio *bio, unsigned int bytes_done, int err)
2096 {
2097         struct packet_stacked_data *psd = bio->bi_private;
2098         struct pktcdvd_device *pd = psd->pd;
2099
2100         if (bio->bi_size)
2101                 return 1;
2102
2103         bio_put(bio);
2104         bio_endio(psd->bio, psd->bio->bi_size, err);
2105         mempool_free(psd, psd_pool);
2106         pkt_bio_finished(pd);
2107         return 0;
2108 }
2109
2110 static int pkt_make_request(request_queue_t *q, struct bio *bio)
2111 {
2112         struct pktcdvd_device *pd;
2113         char b[BDEVNAME_SIZE];
2114         sector_t zone;
2115         struct packet_data *pkt;
2116         int was_empty, blocked_bio;
2117         struct pkt_rb_node *node;
2118
2119         pd = q->queuedata;
2120         if (!pd) {
2121                 printk("pktcdvd: %s incorrect request queue\n", bdevname(bio->bi_bdev, b));
2122                 goto end_io;
2123         }
2124
2125         /*
2126          * Clone READ bios so we can have our own bi_end_io callback.
2127          */
2128         if (bio_data_dir(bio) == READ) {
2129                 struct bio *cloned_bio = bio_clone(bio, GFP_NOIO);
2130                 struct packet_stacked_data *psd = mempool_alloc(psd_pool, GFP_NOIO);
2131
2132                 psd->pd = pd;
2133                 psd->bio = bio;
2134                 cloned_bio->bi_bdev = pd->bdev;
2135                 cloned_bio->bi_private = psd;
2136                 cloned_bio->bi_end_io = pkt_end_io_read_cloned;
2137                 pd->stats.secs_r += bio->bi_size >> 9;
2138                 pkt_queue_bio(pd, cloned_bio);
2139                 return 0;
2140         }
2141
2142         if (!test_bit(PACKET_WRITABLE, &pd->flags)) {
2143                 printk("pktcdvd: WRITE for ro device %s (%llu)\n",
2144                         pd->name, (unsigned long long)bio->bi_sector);
2145                 goto end_io;
2146         }
2147
2148         if (!bio->bi_size || (bio->bi_size % CD_FRAMESIZE)) {
2149                 printk("pktcdvd: wrong bio size\n");
2150                 goto end_io;
2151         }
2152
2153         blk_queue_bounce(q, &bio);
2154
2155         zone = ZONE(bio->bi_sector, pd);
2156         VPRINTK("pkt_make_request: start = %6llx stop = %6llx\n",
2157                 (unsigned long long)bio->bi_sector,
2158                 (unsigned long long)(bio->bi_sector + bio_sectors(bio)));
2159
2160         /* Check if we have to split the bio */
2161         {
2162                 struct bio_pair *bp;
2163                 sector_t last_zone;
2164                 int first_sectors;
2165
2166                 last_zone = ZONE(bio->bi_sector + bio_sectors(bio) - 1, pd);
2167                 if (last_zone != zone) {
2168                         BUG_ON(last_zone != zone + pd->settings.size);
2169                         first_sectors = last_zone - bio->bi_sector;
2170                         bp = bio_split(bio, bio_split_pool, first_sectors);
2171                         BUG_ON(!bp);
2172                         pkt_make_request(q, &bp->bio1);
2173                         pkt_make_request(q, &bp->bio2);
2174                         bio_pair_release(bp);
2175                         return 0;
2176                 }
2177         }
2178
2179         /*
2180          * If we find a matching packet in state WAITING or READ_WAIT, we can
2181          * just append this bio to that packet.
2182          */
2183         spin_lock(&pd->cdrw.active_list_lock);
2184         blocked_bio = 0;
2185         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
2186                 if (pkt->sector == zone) {
2187                         spin_lock(&pkt->lock);
2188                         if ((pkt->state == PACKET_WAITING_STATE) ||
2189                             (pkt->state == PACKET_READ_WAIT_STATE)) {
2190                                 pkt_add_list_last(bio, &pkt->orig_bios,
2191                                                   &pkt->orig_bios_tail);
2192                                 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
2193                                 if ((pkt->write_size >= pkt->frames) &&
2194                                     (pkt->state == PACKET_WAITING_STATE)) {
2195                                         atomic_inc(&pkt->run_sm);
2196                                         wake_up(&pd->wqueue);
2197                                 }
2198                                 spin_unlock(&pkt->lock);
2199                                 spin_unlock(&pd->cdrw.active_list_lock);
2200                                 return 0;
2201                         } else {
2202                                 blocked_bio = 1;
2203                         }
2204                         spin_unlock(&pkt->lock);
2205                 }
2206         }
2207         spin_unlock(&pd->cdrw.active_list_lock);
2208
2209         /*
2210          * No matching packet found. Store the bio in the work queue.
2211          */
2212         node = mempool_alloc(pd->rb_pool, GFP_NOIO);
2213         node->bio = bio;
2214         spin_lock(&pd->lock);
2215         BUG_ON(pd->bio_queue_size < 0);
2216         was_empty = (pd->bio_queue_size == 0);
2217         pkt_rbtree_insert(pd, node);
2218         spin_unlock(&pd->lock);
2219
2220         /*
2221          * Wake up the worker thread.
2222          */
2223         atomic_set(&pd->scan_queue, 1);
2224         if (was_empty) {
2225                 /* This wake_up is required for correct operation */
2226                 wake_up(&pd->wqueue);
2227         } else if (!list_empty(&pd->cdrw.pkt_free_list) && !blocked_bio) {
2228                 /*
2229                  * This wake up is not required for correct operation,
2230                  * but improves performance in some cases.
2231                  */
2232                 wake_up(&pd->wqueue);
2233         }
2234         return 0;
2235 end_io:
2236         bio_io_error(bio, bio->bi_size);
2237         return 0;
2238 }
2239
2240
2241
2242 static int pkt_merge_bvec(request_queue_t *q, struct bio *bio, struct bio_vec *bvec)
2243 {
2244         struct pktcdvd_device *pd = q->queuedata;
2245         sector_t zone = ZONE(bio->bi_sector, pd);
2246         int used = ((bio->bi_sector - zone) << 9) + bio->bi_size;
2247         int remaining = (pd->settings.size << 9) - used;
2248         int remaining2;
2249
2250         /*
2251          * A bio <= PAGE_SIZE must be allowed. If it crosses a packet
2252          * boundary, pkt_make_request() will split the bio.
2253          */
2254         remaining2 = PAGE_SIZE - bio->bi_size;
2255         remaining = max(remaining, remaining2);
2256
2257         BUG_ON(remaining < 0);
2258         return remaining;
2259 }
2260
2261 static void pkt_init_queue(struct pktcdvd_device *pd)
2262 {
2263         request_queue_t *q = pd->disk->queue;
2264
2265         blk_queue_make_request(q, pkt_make_request);
2266         blk_queue_hardsect_size(q, CD_FRAMESIZE);
2267         blk_queue_max_sectors(q, PACKET_MAX_SECTORS);
2268         blk_queue_merge_bvec(q, pkt_merge_bvec);
2269         q->queuedata = pd;
2270 }
2271
2272 static int pkt_seq_show(struct seq_file *m, void *p)
2273 {
2274         struct pktcdvd_device *pd = m->private;
2275         char *msg;
2276         char bdev_buf[BDEVNAME_SIZE];
2277         int states[PACKET_NUM_STATES];
2278
2279         seq_printf(m, "Writer %s mapped to %s:\n", pd->name,
2280                    bdevname(pd->bdev, bdev_buf));
2281
2282         seq_printf(m, "\nSettings:\n");
2283         seq_printf(m, "\tpacket size:\t\t%dkB\n", pd->settings.size / 2);
2284
2285         if (pd->settings.write_type == 0)
2286                 msg = "Packet";
2287         else
2288                 msg = "Unknown";
2289         seq_printf(m, "\twrite type:\t\t%s\n", msg);
2290
2291         seq_printf(m, "\tpacket type:\t\t%s\n", pd->settings.fp ? "Fixed" : "Variable");
2292         seq_printf(m, "\tlink loss:\t\t%d\n", pd->settings.link_loss);
2293
2294         seq_printf(m, "\ttrack mode:\t\t%d\n", pd->settings.track_mode);
2295
2296         if (pd->settings.block_mode == PACKET_BLOCK_MODE1)
2297                 msg = "Mode 1";
2298         else if (pd->settings.block_mode == PACKET_BLOCK_MODE2)
2299                 msg = "Mode 2";
2300         else
2301                 msg = "Unknown";
2302         seq_printf(m, "\tblock mode:\t\t%s\n", msg);
2303
2304         seq_printf(m, "\nStatistics:\n");
2305         seq_printf(m, "\tpackets started:\t%lu\n", pd->stats.pkt_started);
2306         seq_printf(m, "\tpackets ended:\t\t%lu\n", pd->stats.pkt_ended);
2307         seq_printf(m, "\twritten:\t\t%lukB\n", pd->stats.secs_w >> 1);
2308         seq_printf(m, "\tread gather:\t\t%lukB\n", pd->stats.secs_rg >> 1);
2309         seq_printf(m, "\tread:\t\t\t%lukB\n", pd->stats.secs_r >> 1);
2310
2311         seq_printf(m, "\nMisc:\n");
2312         seq_printf(m, "\treference count:\t%d\n", pd->refcnt);
2313         seq_printf(m, "\tflags:\t\t\t0x%lx\n", pd->flags);
2314         seq_printf(m, "\tread speed:\t\t%ukB/s\n", pd->read_speed);
2315         seq_printf(m, "\twrite speed:\t\t%ukB/s\n", pd->write_speed);
2316         seq_printf(m, "\tstart offset:\t\t%lu\n", pd->offset);
2317         seq_printf(m, "\tmode page offset:\t%u\n", pd->mode_offset);
2318
2319         seq_printf(m, "\nQueue state:\n");
2320         seq_printf(m, "\tbios queued:\t\t%d\n", pd->bio_queue_size);
2321         seq_printf(m, "\tbios pending:\t\t%d\n", atomic_read(&pd->cdrw.pending_bios));
2322         seq_printf(m, "\tcurrent sector:\t\t0x%llx\n", (unsigned long long)pd->current_sector);
2323
2324         pkt_count_states(pd, states);
2325         seq_printf(m, "\tstate:\t\t\ti:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
2326                    states[0], states[1], states[2], states[3], states[4], states[5]);
2327
2328         return 0;
2329 }
2330
2331 static int pkt_seq_open(struct inode *inode, struct file *file)
2332 {
2333         return single_open(file, pkt_seq_show, PDE(inode)->data);
2334 }
2335
2336 static struct file_operations pkt_proc_fops = {
2337         .open   = pkt_seq_open,
2338         .read   = seq_read,
2339         .llseek = seq_lseek,
2340         .release = single_release
2341 };
2342
2343 static int pkt_new_dev(struct pktcdvd_device *pd, dev_t dev)
2344 {
2345         int i;
2346         int ret = 0;
2347         char b[BDEVNAME_SIZE];
2348         struct proc_dir_entry *proc;
2349         struct block_device *bdev;
2350
2351         if (pd->pkt_dev == dev) {
2352                 printk("pktcdvd: Recursive setup not allowed\n");
2353                 return -EBUSY;
2354         }
2355         for (i = 0; i < MAX_WRITERS; i++) {
2356                 struct pktcdvd_device *pd2 = pkt_devs[i];
2357                 if (!pd2)
2358                         continue;
2359                 if (pd2->bdev->bd_dev == dev) {
2360                         printk("pktcdvd: %s already setup\n", bdevname(pd2->bdev, b));
2361                         return -EBUSY;
2362                 }
2363                 if (pd2->pkt_dev == dev) {
2364                         printk("pktcdvd: Can't chain pktcdvd devices\n");
2365                         return -EBUSY;
2366                 }
2367         }
2368
2369         bdev = bdget(dev);
2370         if (!bdev)
2371                 return -ENOMEM;
2372         ret = blkdev_get(bdev, FMODE_READ, O_RDONLY | O_NONBLOCK);
2373         if (ret)
2374                 return ret;
2375
2376         /* This is safe, since we have a reference from open(). */
2377         __module_get(THIS_MODULE);
2378
2379         if (!pkt_grow_pktlist(pd, CONFIG_CDROM_PKTCDVD_BUFFERS)) {
2380                 printk("pktcdvd: not enough memory for buffers\n");
2381                 ret = -ENOMEM;
2382                 goto out_mem;
2383         }
2384
2385         pd->bdev = bdev;
2386         set_blocksize(bdev, CD_FRAMESIZE);
2387
2388         pkt_init_queue(pd);
2389
2390         atomic_set(&pd->cdrw.pending_bios, 0);
2391         pd->cdrw.thread = kthread_run(kcdrwd, pd, "%s", pd->name);
2392         if (IS_ERR(pd->cdrw.thread)) {
2393                 printk("pktcdvd: can't start kernel thread\n");
2394                 ret = -ENOMEM;
2395                 goto out_thread;
2396         }
2397
2398         proc = create_proc_entry(pd->name, 0, pkt_proc);
2399         if (proc) {
2400                 proc->data = pd;
2401                 proc->proc_fops = &pkt_proc_fops;
2402         }
2403         DPRINTK("pktcdvd: writer %s mapped to %s\n", pd->name, bdevname(bdev, b));
2404         return 0;
2405
2406 out_thread:
2407         pkt_shrink_pktlist(pd);
2408 out_mem:
2409         blkdev_put(bdev);
2410         /* This is safe: open() is still holding a reference. */
2411         module_put(THIS_MODULE);
2412         return ret;
2413 }
2414
2415 static int pkt_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2416 {
2417         struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2418
2419         VPRINTK("pkt_ioctl: cmd %x, dev %d:%d\n", cmd, imajor(inode), iminor(inode));
2420
2421         switch (cmd) {
2422         /*
2423          * forward selected CDROM ioctls to CD-ROM, for UDF
2424          */
2425         case CDROMMULTISESSION:
2426         case CDROMREADTOCENTRY:
2427         case CDROM_LAST_WRITTEN:
2428         case CDROM_SEND_PACKET:
2429         case SCSI_IOCTL_SEND_COMMAND:
2430                 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2431
2432         case CDROMEJECT:
2433                 /*
2434                  * The door gets locked when the device is opened, so we
2435                  * have to unlock it or else the eject command fails.
2436                  */
2437                 pkt_lock_door(pd, 0);
2438                 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2439
2440         default:
2441                 printk("pktcdvd: Unknown ioctl for %s (%x)\n", pd->name, cmd);
2442                 return -ENOTTY;
2443         }
2444
2445         return 0;
2446 }
2447
2448 static int pkt_media_changed(struct gendisk *disk)
2449 {
2450         struct pktcdvd_device *pd = disk->private_data;
2451         struct gendisk *attached_disk;
2452
2453         if (!pd)
2454                 return 0;
2455         if (!pd->bdev)
2456                 return 0;
2457         attached_disk = pd->bdev->bd_disk;
2458         if (!attached_disk)
2459                 return 0;
2460         return attached_disk->fops->media_changed(attached_disk);
2461 }
2462
2463 static struct block_device_operations pktcdvd_ops = {
2464         .owner =                THIS_MODULE,
2465         .open =                 pkt_open,
2466         .release =              pkt_close,
2467         .ioctl =                pkt_ioctl,
2468         .media_changed =        pkt_media_changed,
2469 };
2470
2471 /*
2472  * Set up mapping from pktcdvd device to CD-ROM device.
2473  */
2474 static int pkt_setup_dev(struct pkt_ctrl_command *ctrl_cmd)
2475 {
2476         int idx;
2477         int ret = -ENOMEM;
2478         struct pktcdvd_device *pd;
2479         struct gendisk *disk;
2480         dev_t dev = new_decode_dev(ctrl_cmd->dev);
2481
2482         for (idx = 0; idx < MAX_WRITERS; idx++)
2483                 if (!pkt_devs[idx])
2484                         break;
2485         if (idx == MAX_WRITERS) {
2486                 printk("pktcdvd: max %d writers supported\n", MAX_WRITERS);
2487                 return -EBUSY;
2488         }
2489
2490         pd = kzalloc(sizeof(struct pktcdvd_device), GFP_KERNEL);
2491         if (!pd)
2492                 return ret;
2493
2494         pd->rb_pool = mempool_create(PKT_RB_POOL_SIZE, pkt_rb_alloc, pkt_rb_free, NULL);
2495         if (!pd->rb_pool)
2496                 goto out_mem;
2497
2498         disk = alloc_disk(1);
2499         if (!disk)
2500                 goto out_mem;
2501         pd->disk = disk;
2502
2503         spin_lock_init(&pd->lock);
2504         spin_lock_init(&pd->iosched.lock);
2505         sprintf(pd->name, "pktcdvd%d", idx);
2506         init_waitqueue_head(&pd->wqueue);
2507         pd->bio_queue = RB_ROOT;
2508
2509         disk->major = pkt_major;
2510         disk->first_minor = idx;
2511         disk->fops = &pktcdvd_ops;
2512         disk->flags = GENHD_FL_REMOVABLE;
2513         sprintf(disk->disk_name, "pktcdvd%d", idx);
2514         disk->private_data = pd;
2515         disk->queue = blk_alloc_queue(GFP_KERNEL);
2516         if (!disk->queue)
2517                 goto out_mem2;
2518
2519         pd->pkt_dev = MKDEV(disk->major, disk->first_minor);
2520         ret = pkt_new_dev(pd, dev);
2521         if (ret)
2522                 goto out_new_dev;
2523
2524         add_disk(disk);
2525         pkt_devs[idx] = pd;
2526         ctrl_cmd->pkt_dev = new_encode_dev(pd->pkt_dev);
2527         return 0;
2528
2529 out_new_dev:
2530         blk_put_queue(disk->queue);
2531 out_mem2:
2532         put_disk(disk);
2533 out_mem:
2534         if (pd->rb_pool)
2535                 mempool_destroy(pd->rb_pool);
2536         kfree(pd);
2537         return ret;
2538 }
2539
2540 /*
2541  * Tear down mapping from pktcdvd device to CD-ROM device.
2542  */
2543 static int pkt_remove_dev(struct pkt_ctrl_command *ctrl_cmd)
2544 {
2545         struct pktcdvd_device *pd;
2546         int idx;
2547         dev_t pkt_dev = new_decode_dev(ctrl_cmd->pkt_dev);
2548
2549         for (idx = 0; idx < MAX_WRITERS; idx++) {
2550                 pd = pkt_devs[idx];
2551                 if (pd && (pd->pkt_dev == pkt_dev))
2552                         break;
2553         }
2554         if (idx == MAX_WRITERS) {
2555                 DPRINTK("pktcdvd: dev not setup\n");
2556                 return -ENXIO;
2557         }
2558
2559         if (pd->refcnt > 0)
2560                 return -EBUSY;
2561
2562         if (!IS_ERR(pd->cdrw.thread))
2563                 kthread_stop(pd->cdrw.thread);
2564
2565         blkdev_put(pd->bdev);
2566
2567         pkt_shrink_pktlist(pd);
2568
2569         remove_proc_entry(pd->name, pkt_proc);
2570         DPRINTK("pktcdvd: writer %s unmapped\n", pd->name);
2571
2572         del_gendisk(pd->disk);
2573         blk_put_queue(pd->disk->queue);
2574         put_disk(pd->disk);
2575
2576         pkt_devs[idx] = NULL;
2577         mempool_destroy(pd->rb_pool);
2578         kfree(pd);
2579
2580         /* This is safe: open() is still holding a reference. */
2581         module_put(THIS_MODULE);
2582         return 0;
2583 }
2584
2585 static void pkt_get_status(struct pkt_ctrl_command *ctrl_cmd)
2586 {
2587         struct pktcdvd_device *pd = pkt_find_dev_from_minor(ctrl_cmd->dev_index);
2588         if (pd) {
2589                 ctrl_cmd->dev = new_encode_dev(pd->bdev->bd_dev);
2590                 ctrl_cmd->pkt_dev = new_encode_dev(pd->pkt_dev);
2591         } else {
2592                 ctrl_cmd->dev = 0;
2593                 ctrl_cmd->pkt_dev = 0;
2594         }
2595         ctrl_cmd->num_devices = MAX_WRITERS;
2596 }
2597
2598 static int pkt_ctl_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2599 {
2600         void __user *argp = (void __user *)arg;
2601         struct pkt_ctrl_command ctrl_cmd;
2602         int ret = 0;
2603
2604         if (cmd != PACKET_CTRL_CMD)
2605                 return -ENOTTY;
2606
2607         if (copy_from_user(&ctrl_cmd, argp, sizeof(struct pkt_ctrl_command)))
2608                 return -EFAULT;
2609
2610         switch (ctrl_cmd.command) {
2611         case PKT_CTRL_CMD_SETUP:
2612                 if (!capable(CAP_SYS_ADMIN))
2613                         return -EPERM;
2614                 down(&ctl_mutex);
2615                 ret = pkt_setup_dev(&ctrl_cmd);
2616                 up(&ctl_mutex);
2617                 break;
2618         case PKT_CTRL_CMD_TEARDOWN:
2619                 if (!capable(CAP_SYS_ADMIN))
2620                         return -EPERM;
2621                 down(&ctl_mutex);
2622                 ret = pkt_remove_dev(&ctrl_cmd);
2623                 up(&ctl_mutex);
2624                 break;
2625         case PKT_CTRL_CMD_STATUS:
2626                 down(&ctl_mutex);
2627                 pkt_get_status(&ctrl_cmd);
2628                 up(&ctl_mutex);
2629                 break;
2630         default:
2631                 return -ENOTTY;
2632         }
2633
2634         if (copy_to_user(argp, &ctrl_cmd, sizeof(struct pkt_ctrl_command)))
2635                 return -EFAULT;
2636         return ret;
2637 }
2638
2639
2640 static struct file_operations pkt_ctl_fops = {
2641         .ioctl   = pkt_ctl_ioctl,
2642         .owner   = THIS_MODULE,
2643 };
2644
2645 static struct miscdevice pkt_misc = {
2646         .minor          = MISC_DYNAMIC_MINOR,
2647         .name           = "pktcdvd",
2648         .devfs_name     = "pktcdvd/control",
2649         .fops           = &pkt_ctl_fops
2650 };
2651
2652 static int __init pkt_init(void)
2653 {
2654         int ret;
2655
2656         psd_pool = mempool_create(PSD_POOL_SIZE, psd_pool_alloc, psd_pool_free, NULL);
2657         if (!psd_pool)
2658                 return -ENOMEM;
2659
2660         ret = register_blkdev(pkt_major, "pktcdvd");
2661         if (ret < 0) {
2662                 printk("pktcdvd: Unable to register block device\n");
2663                 goto out2;
2664         }
2665         if (!pkt_major)
2666                 pkt_major = ret;
2667
2668         ret = misc_register(&pkt_misc);
2669         if (ret) {
2670                 printk("pktcdvd: Unable to register misc device\n");
2671                 goto out;
2672         }
2673
2674         init_MUTEX(&ctl_mutex);
2675
2676         pkt_proc = proc_mkdir("pktcdvd", proc_root_driver);
2677
2678         DPRINTK("pktcdvd: %s\n", VERSION_CODE);
2679         return 0;
2680
2681 out:
2682         unregister_blkdev(pkt_major, "pktcdvd");
2683 out2:
2684         mempool_destroy(psd_pool);
2685         return ret;
2686 }
2687
2688 static void __exit pkt_exit(void)
2689 {
2690         remove_proc_entry("pktcdvd", proc_root_driver);
2691         misc_deregister(&pkt_misc);
2692         unregister_blkdev(pkt_major, "pktcdvd");
2693         mempool_destroy(psd_pool);
2694 }
2695
2696 MODULE_DESCRIPTION("Packet writing layer for CD/DVD drives");
2697 MODULE_AUTHOR("Jens Axboe <axboe@suse.de>");
2698 MODULE_LICENSE("GPL");
2699
2700 module_init(pkt_init);
2701 module_exit(pkt_exit);