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