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