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>
6 * May be copied or modified under the terms of the GNU General Public
7 * License. See linux/COPYING for more information.
9 * Packet writing layer for ATAPI and SCSI CD-RW, DVD+RW, DVD-RW and
12 * Theory of operation:
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.
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.
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.
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.
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.
45 *************************************************************************/
47 #include <linux/pktcdvd.h>
48 #include <linux/module.h>
49 #include <linux/types.h>
50 #include <linux/kernel.h>
51 #include <linux/kthread.h>
52 #include <linux/errno.h>
53 #include <linux/spinlock.h>
54 #include <linux/file.h>
55 #include <linux/proc_fs.h>
56 #include <linux/seq_file.h>
57 #include <linux/miscdevice.h>
58 #include <linux/freezer.h>
59 #include <linux/mutex.h>
60 #include <scsi/scsi_cmnd.h>
61 #include <scsi/scsi_ioctl.h>
62 #include <scsi/scsi.h>
63 #include <linux/debugfs.h>
64 #include <linux/device.h>
66 #include <asm/uaccess.h>
68 #define DRIVER_NAME "pktcdvd"
71 #define DPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
73 #define DPRINTK(fmt, args...)
77 #define VPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
79 #define VPRINTK(fmt, args...)
82 #define MAX_SPEED 0xffff
84 #define ZONE(sector, pd) (((sector) + (pd)->offset) & ~((pd)->settings.size - 1))
86 static struct pktcdvd_device *pkt_devs[MAX_WRITERS];
87 static struct proc_dir_entry *pkt_proc;
88 static int pktdev_major;
89 static int write_congestion_on = PKT_WRITE_CONGESTION_ON;
90 static int write_congestion_off = PKT_WRITE_CONGESTION_OFF;
91 static struct mutex ctl_mutex; /* Serialize open/close/setup/teardown */
92 static mempool_t *psd_pool;
94 static struct class *class_pktcdvd = NULL; /* /sys/class/pktcdvd */
95 static struct dentry *pkt_debugfs_root = NULL; /* /debug/pktcdvd */
97 /* forward declaration */
98 static int pkt_setup_dev(dev_t dev, dev_t* pkt_dev);
99 static int pkt_remove_dev(dev_t pkt_dev);
100 static int pkt_seq_show(struct seq_file *m, void *p);
105 * create and register a pktcdvd kernel object.
107 static struct pktcdvd_kobj* pkt_kobj_create(struct pktcdvd_device *pd,
109 struct kobject* parent,
110 struct kobj_type* ktype)
112 struct pktcdvd_kobj *p;
113 p = kzalloc(sizeof(*p), GFP_KERNEL);
116 kobject_set_name(&p->kobj, "%s", name);
117 p->kobj.parent = parent;
118 p->kobj.ktype = ktype;
120 if (kobject_register(&p->kobj) != 0)
125 * remove a pktcdvd kernel object.
127 static void pkt_kobj_remove(struct pktcdvd_kobj *p)
130 kobject_unregister(&p->kobj);
133 * default release function for pktcdvd kernel objects.
135 static void pkt_kobj_release(struct kobject *kobj)
137 kfree(to_pktcdvdkobj(kobj));
141 /**********************************************************
143 * sysfs interface for pktcdvd
144 * by (C) 2006 Thomas Maier <balagi@justmail.de>
146 **********************************************************/
148 #define DEF_ATTR(_obj,_name,_mode) \
149 static struct attribute _obj = { .name = _name, .mode = _mode }
151 /**********************************************************
152 /sys/class/pktcdvd/pktcdvd[0-7]/
155 stat/packets_finished
160 write_queue/congestion_off
161 write_queue/congestion_on
162 **********************************************************/
164 DEF_ATTR(kobj_pkt_attr_st1, "reset", 0200);
165 DEF_ATTR(kobj_pkt_attr_st2, "packets_started", 0444);
166 DEF_ATTR(kobj_pkt_attr_st3, "packets_finished", 0444);
167 DEF_ATTR(kobj_pkt_attr_st4, "kb_written", 0444);
168 DEF_ATTR(kobj_pkt_attr_st5, "kb_read", 0444);
169 DEF_ATTR(kobj_pkt_attr_st6, "kb_read_gather", 0444);
171 static struct attribute *kobj_pkt_attrs_stat[] = {
181 DEF_ATTR(kobj_pkt_attr_wq1, "size", 0444);
182 DEF_ATTR(kobj_pkt_attr_wq2, "congestion_off", 0644);
183 DEF_ATTR(kobj_pkt_attr_wq3, "congestion_on", 0644);
185 static struct attribute *kobj_pkt_attrs_wqueue[] = {
192 static ssize_t kobj_pkt_show(struct kobject *kobj,
193 struct attribute *attr, char *data)
195 struct pktcdvd_device *pd = to_pktcdvdkobj(kobj)->pd;
198 if (strcmp(attr->name, "packets_started") == 0) {
199 n = sprintf(data, "%lu\n", pd->stats.pkt_started);
201 } else if (strcmp(attr->name, "packets_finished") == 0) {
202 n = sprintf(data, "%lu\n", pd->stats.pkt_ended);
204 } else if (strcmp(attr->name, "kb_written") == 0) {
205 n = sprintf(data, "%lu\n", pd->stats.secs_w >> 1);
207 } else if (strcmp(attr->name, "kb_read") == 0) {
208 n = sprintf(data, "%lu\n", pd->stats.secs_r >> 1);
210 } else if (strcmp(attr->name, "kb_read_gather") == 0) {
211 n = sprintf(data, "%lu\n", pd->stats.secs_rg >> 1);
213 } else if (strcmp(attr->name, "size") == 0) {
214 spin_lock(&pd->lock);
215 v = pd->bio_queue_size;
216 spin_unlock(&pd->lock);
217 n = sprintf(data, "%d\n", v);
219 } else if (strcmp(attr->name, "congestion_off") == 0) {
220 spin_lock(&pd->lock);
221 v = pd->write_congestion_off;
222 spin_unlock(&pd->lock);
223 n = sprintf(data, "%d\n", v);
225 } else if (strcmp(attr->name, "congestion_on") == 0) {
226 spin_lock(&pd->lock);
227 v = pd->write_congestion_on;
228 spin_unlock(&pd->lock);
229 n = sprintf(data, "%d\n", v);
234 static void init_write_congestion_marks(int* lo, int* hi)
238 *hi = min(*hi, 1000000);
242 *lo = min(*lo, *hi - 100);
251 static ssize_t kobj_pkt_store(struct kobject *kobj,
252 struct attribute *attr,
253 const char *data, size_t len)
255 struct pktcdvd_device *pd = to_pktcdvdkobj(kobj)->pd;
258 if (strcmp(attr->name, "reset") == 0 && len > 0) {
259 pd->stats.pkt_started = 0;
260 pd->stats.pkt_ended = 0;
261 pd->stats.secs_w = 0;
262 pd->stats.secs_rg = 0;
263 pd->stats.secs_r = 0;
265 } else if (strcmp(attr->name, "congestion_off") == 0
266 && sscanf(data, "%d", &val) == 1) {
267 spin_lock(&pd->lock);
268 pd->write_congestion_off = val;
269 init_write_congestion_marks(&pd->write_congestion_off,
270 &pd->write_congestion_on);
271 spin_unlock(&pd->lock);
273 } else if (strcmp(attr->name, "congestion_on") == 0
274 && sscanf(data, "%d", &val) == 1) {
275 spin_lock(&pd->lock);
276 pd->write_congestion_on = val;
277 init_write_congestion_marks(&pd->write_congestion_off,
278 &pd->write_congestion_on);
279 spin_unlock(&pd->lock);
284 static struct sysfs_ops kobj_pkt_ops = {
285 .show = kobj_pkt_show,
286 .store = kobj_pkt_store
288 static struct kobj_type kobj_pkt_type_stat = {
289 .release = pkt_kobj_release,
290 .sysfs_ops = &kobj_pkt_ops,
291 .default_attrs = kobj_pkt_attrs_stat
293 static struct kobj_type kobj_pkt_type_wqueue = {
294 .release = pkt_kobj_release,
295 .sysfs_ops = &kobj_pkt_ops,
296 .default_attrs = kobj_pkt_attrs_wqueue
299 static void pkt_sysfs_dev_new(struct pktcdvd_device *pd)
302 pd->clsdev = class_device_create(class_pktcdvd,
304 NULL, "%s", pd->name);
305 if (IS_ERR(pd->clsdev))
309 pd->kobj_stat = pkt_kobj_create(pd, "stat",
311 &kobj_pkt_type_stat);
312 pd->kobj_wqueue = pkt_kobj_create(pd, "write_queue",
314 &kobj_pkt_type_wqueue);
318 static void pkt_sysfs_dev_remove(struct pktcdvd_device *pd)
320 pkt_kobj_remove(pd->kobj_stat);
321 pkt_kobj_remove(pd->kobj_wqueue);
323 class_device_destroy(class_pktcdvd, pd->pkt_dev);
327 /********************************************************************
330 remove unmap packet dev
331 device_map show mappings
332 *******************************************************************/
334 static void class_pktcdvd_release(struct class *cls)
338 static ssize_t class_pktcdvd_show_map(struct class *c, char *data)
342 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
343 for (idx = 0; idx < MAX_WRITERS; idx++) {
344 struct pktcdvd_device *pd = pkt_devs[idx];
347 n += sprintf(data+n, "%s %u:%u %u:%u\n",
349 MAJOR(pd->pkt_dev), MINOR(pd->pkt_dev),
350 MAJOR(pd->bdev->bd_dev),
351 MINOR(pd->bdev->bd_dev));
353 mutex_unlock(&ctl_mutex);
357 static ssize_t class_pktcdvd_store_add(struct class *c, const char *buf,
360 unsigned int major, minor;
361 if (sscanf(buf, "%u:%u", &major, &minor) == 2) {
362 pkt_setup_dev(MKDEV(major, minor), NULL);
368 static ssize_t class_pktcdvd_store_remove(struct class *c, const char *buf,
371 unsigned int major, minor;
372 if (sscanf(buf, "%u:%u", &major, &minor) == 2) {
373 pkt_remove_dev(MKDEV(major, minor));
379 static struct class_attribute class_pktcdvd_attrs[] = {
380 __ATTR(add, 0200, NULL, class_pktcdvd_store_add),
381 __ATTR(remove, 0200, NULL, class_pktcdvd_store_remove),
382 __ATTR(device_map, 0444, class_pktcdvd_show_map, NULL),
387 static int pkt_sysfs_init(void)
392 * create control files in sysfs
393 * /sys/class/pktcdvd/...
395 class_pktcdvd = kzalloc(sizeof(*class_pktcdvd), GFP_KERNEL);
398 class_pktcdvd->name = DRIVER_NAME;
399 class_pktcdvd->owner = THIS_MODULE;
400 class_pktcdvd->class_release = class_pktcdvd_release;
401 class_pktcdvd->class_attrs = class_pktcdvd_attrs;
402 ret = class_register(class_pktcdvd);
404 kfree(class_pktcdvd);
405 class_pktcdvd = NULL;
406 printk(DRIVER_NAME": failed to create class pktcdvd\n");
412 static void pkt_sysfs_cleanup(void)
415 class_destroy(class_pktcdvd);
416 class_pktcdvd = NULL;
419 /********************************************************************
422 /debugfs/pktcdvd[0-7]/
425 *******************************************************************/
427 static int pkt_debugfs_seq_show(struct seq_file *m, void *p)
429 return pkt_seq_show(m, p);
432 static int pkt_debugfs_fops_open(struct inode *inode, struct file *file)
434 return single_open(file, pkt_debugfs_seq_show, inode->i_private);
437 static const struct file_operations debug_fops = {
438 .open = pkt_debugfs_fops_open,
441 .release = single_release,
442 .owner = THIS_MODULE,
445 static void pkt_debugfs_dev_new(struct pktcdvd_device *pd)
447 if (!pkt_debugfs_root)
449 pd->dfs_f_info = NULL;
450 pd->dfs_d_root = debugfs_create_dir(pd->name, pkt_debugfs_root);
451 if (IS_ERR(pd->dfs_d_root)) {
452 pd->dfs_d_root = NULL;
455 pd->dfs_f_info = debugfs_create_file("info", S_IRUGO,
456 pd->dfs_d_root, pd, &debug_fops);
457 if (IS_ERR(pd->dfs_f_info)) {
458 pd->dfs_f_info = NULL;
463 static void pkt_debugfs_dev_remove(struct pktcdvd_device *pd)
465 if (!pkt_debugfs_root)
468 debugfs_remove(pd->dfs_f_info);
469 pd->dfs_f_info = NULL;
471 debugfs_remove(pd->dfs_d_root);
472 pd->dfs_d_root = NULL;
475 static void pkt_debugfs_init(void)
477 pkt_debugfs_root = debugfs_create_dir(DRIVER_NAME, NULL);
478 if (IS_ERR(pkt_debugfs_root)) {
479 pkt_debugfs_root = NULL;
484 static void pkt_debugfs_cleanup(void)
486 if (!pkt_debugfs_root)
488 debugfs_remove(pkt_debugfs_root);
489 pkt_debugfs_root = NULL;
492 /* ----------------------------------------------------------*/
495 static void pkt_bio_finished(struct pktcdvd_device *pd)
497 BUG_ON(atomic_read(&pd->cdrw.pending_bios) <= 0);
498 if (atomic_dec_and_test(&pd->cdrw.pending_bios)) {
499 VPRINTK(DRIVER_NAME": queue empty\n");
500 atomic_set(&pd->iosched.attention, 1);
501 wake_up(&pd->wqueue);
505 static void pkt_bio_destructor(struct bio *bio)
507 kfree(bio->bi_io_vec);
511 static struct bio *pkt_bio_alloc(int nr_iovecs)
513 struct bio_vec *bvl = NULL;
516 bio = kmalloc(sizeof(struct bio), GFP_KERNEL);
521 bvl = kcalloc(nr_iovecs, sizeof(struct bio_vec), GFP_KERNEL);
525 bio->bi_max_vecs = nr_iovecs;
526 bio->bi_io_vec = bvl;
527 bio->bi_destructor = pkt_bio_destructor;
538 * Allocate a packet_data struct
540 static struct packet_data *pkt_alloc_packet_data(int frames)
543 struct packet_data *pkt;
545 pkt = kzalloc(sizeof(struct packet_data), GFP_KERNEL);
549 pkt->frames = frames;
550 pkt->w_bio = pkt_bio_alloc(frames);
554 for (i = 0; i < frames / FRAMES_PER_PAGE; i++) {
555 pkt->pages[i] = alloc_page(GFP_KERNEL|__GFP_ZERO);
560 spin_lock_init(&pkt->lock);
562 for (i = 0; i < frames; i++) {
563 struct bio *bio = pkt_bio_alloc(1);
566 pkt->r_bios[i] = bio;
572 for (i = 0; i < frames; i++) {
573 struct bio *bio = pkt->r_bios[i];
579 for (i = 0; i < frames / FRAMES_PER_PAGE; i++)
581 __free_page(pkt->pages[i]);
590 * Free a packet_data struct
592 static void pkt_free_packet_data(struct packet_data *pkt)
596 for (i = 0; i < pkt->frames; i++) {
597 struct bio *bio = pkt->r_bios[i];
601 for (i = 0; i < pkt->frames / FRAMES_PER_PAGE; i++)
602 __free_page(pkt->pages[i]);
607 static void pkt_shrink_pktlist(struct pktcdvd_device *pd)
609 struct packet_data *pkt, *next;
611 BUG_ON(!list_empty(&pd->cdrw.pkt_active_list));
613 list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_free_list, list) {
614 pkt_free_packet_data(pkt);
616 INIT_LIST_HEAD(&pd->cdrw.pkt_free_list);
619 static int pkt_grow_pktlist(struct pktcdvd_device *pd, int nr_packets)
621 struct packet_data *pkt;
623 BUG_ON(!list_empty(&pd->cdrw.pkt_free_list));
625 while (nr_packets > 0) {
626 pkt = pkt_alloc_packet_data(pd->settings.size >> 2);
628 pkt_shrink_pktlist(pd);
631 pkt->id = nr_packets;
633 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
639 static inline struct pkt_rb_node *pkt_rbtree_next(struct pkt_rb_node *node)
641 struct rb_node *n = rb_next(&node->rb_node);
644 return rb_entry(n, struct pkt_rb_node, rb_node);
647 static void pkt_rbtree_erase(struct pktcdvd_device *pd, struct pkt_rb_node *node)
649 rb_erase(&node->rb_node, &pd->bio_queue);
650 mempool_free(node, pd->rb_pool);
651 pd->bio_queue_size--;
652 BUG_ON(pd->bio_queue_size < 0);
656 * Find the first node in the pd->bio_queue rb tree with a starting sector >= s.
658 static struct pkt_rb_node *pkt_rbtree_find(struct pktcdvd_device *pd, sector_t s)
660 struct rb_node *n = pd->bio_queue.rb_node;
661 struct rb_node *next;
662 struct pkt_rb_node *tmp;
665 BUG_ON(pd->bio_queue_size > 0);
670 tmp = rb_entry(n, struct pkt_rb_node, rb_node);
671 if (s <= tmp->bio->bi_sector)
680 if (s > tmp->bio->bi_sector) {
681 tmp = pkt_rbtree_next(tmp);
685 BUG_ON(s > tmp->bio->bi_sector);
690 * Insert a node into the pd->bio_queue rb tree.
692 static void pkt_rbtree_insert(struct pktcdvd_device *pd, struct pkt_rb_node *node)
694 struct rb_node **p = &pd->bio_queue.rb_node;
695 struct rb_node *parent = NULL;
696 sector_t s = node->bio->bi_sector;
697 struct pkt_rb_node *tmp;
701 tmp = rb_entry(parent, struct pkt_rb_node, rb_node);
702 if (s < tmp->bio->bi_sector)
707 rb_link_node(&node->rb_node, parent, p);
708 rb_insert_color(&node->rb_node, &pd->bio_queue);
709 pd->bio_queue_size++;
713 * Add a bio to a single linked list defined by its head and tail pointers.
715 static void pkt_add_list_last(struct bio *bio, struct bio **list_head, struct bio **list_tail)
719 BUG_ON((*list_head) == NULL);
720 (*list_tail)->bi_next = bio;
723 BUG_ON((*list_head) != NULL);
730 * Remove and return the first bio from a single linked list defined by its
731 * head and tail pointers.
733 static inline struct bio *pkt_get_list_first(struct bio **list_head, struct bio **list_tail)
737 if (*list_head == NULL)
741 *list_head = bio->bi_next;
742 if (*list_head == NULL)
750 * Send a packet_command to the underlying block device and
751 * wait for completion.
753 static int pkt_generic_packet(struct pktcdvd_device *pd, struct packet_command *cgc)
755 struct request_queue *q = bdev_get_queue(pd->bdev);
759 rq = blk_get_request(q, (cgc->data_direction == CGC_DATA_WRITE) ?
760 WRITE : READ, __GFP_WAIT);
763 if (blk_rq_map_kern(q, rq, cgc->buffer, cgc->buflen, __GFP_WAIT))
767 rq->cmd_len = COMMAND_SIZE(cgc->cmd[0]);
768 memcpy(rq->cmd, cgc->cmd, CDROM_PACKET_SIZE);
769 if (sizeof(rq->cmd) > CDROM_PACKET_SIZE)
770 memset(rq->cmd + CDROM_PACKET_SIZE, 0, sizeof(rq->cmd) - CDROM_PACKET_SIZE);
773 rq->cmd_type = REQ_TYPE_BLOCK_PC;
774 rq->cmd_flags |= REQ_HARDBARRIER;
776 rq->cmd_flags |= REQ_QUIET;
778 blk_execute_rq(rq->q, pd->bdev->bd_disk, rq, 0);
787 * A generic sense dump / resolve mechanism should be implemented across
788 * all ATAPI + SCSI devices.
790 static void pkt_dump_sense(struct packet_command *cgc)
792 static char *info[9] = { "No sense", "Recovered error", "Not ready",
793 "Medium error", "Hardware error", "Illegal request",
794 "Unit attention", "Data protect", "Blank check" };
796 struct request_sense *sense = cgc->sense;
798 printk(DRIVER_NAME":");
799 for (i = 0; i < CDROM_PACKET_SIZE; i++)
800 printk(" %02x", cgc->cmd[i]);
804 printk("no sense\n");
808 printk("sense %02x.%02x.%02x", sense->sense_key, sense->asc, sense->ascq);
810 if (sense->sense_key > 8) {
811 printk(" (INVALID)\n");
815 printk(" (%s)\n", info[sense->sense_key]);
819 * flush the drive cache to media
821 static int pkt_flush_cache(struct pktcdvd_device *pd)
823 struct packet_command cgc;
825 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
826 cgc.cmd[0] = GPCMD_FLUSH_CACHE;
830 * the IMMED bit -- we default to not setting it, although that
831 * would allow a much faster close, this is safer
836 return pkt_generic_packet(pd, &cgc);
840 * speed is given as the normal factor, e.g. 4 for 4x
842 static int pkt_set_speed(struct pktcdvd_device *pd, unsigned write_speed, unsigned read_speed)
844 struct packet_command cgc;
845 struct request_sense sense;
848 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
850 cgc.cmd[0] = GPCMD_SET_SPEED;
851 cgc.cmd[2] = (read_speed >> 8) & 0xff;
852 cgc.cmd[3] = read_speed & 0xff;
853 cgc.cmd[4] = (write_speed >> 8) & 0xff;
854 cgc.cmd[5] = write_speed & 0xff;
856 if ((ret = pkt_generic_packet(pd, &cgc)))
857 pkt_dump_sense(&cgc);
863 * Queue a bio for processing by the low-level CD device. Must be called
864 * from process context.
866 static void pkt_queue_bio(struct pktcdvd_device *pd, struct bio *bio)
868 spin_lock(&pd->iosched.lock);
869 if (bio_data_dir(bio) == READ) {
870 pkt_add_list_last(bio, &pd->iosched.read_queue,
871 &pd->iosched.read_queue_tail);
873 pkt_add_list_last(bio, &pd->iosched.write_queue,
874 &pd->iosched.write_queue_tail);
876 spin_unlock(&pd->iosched.lock);
878 atomic_set(&pd->iosched.attention, 1);
879 wake_up(&pd->wqueue);
883 * Process the queued read/write requests. This function handles special
884 * requirements for CDRW drives:
885 * - A cache flush command must be inserted before a read request if the
886 * previous request was a write.
887 * - Switching between reading and writing is slow, so don't do it more often
889 * - Optimize for throughput at the expense of latency. This means that streaming
890 * writes will never be interrupted by a read, but if the drive has to seek
891 * before the next write, switch to reading instead if there are any pending
893 * - Set the read speed according to current usage pattern. When only reading
894 * from the device, it's best to use the highest possible read speed, but
895 * when switching often between reading and writing, it's better to have the
896 * same read and write speeds.
898 static void pkt_iosched_process_queue(struct pktcdvd_device *pd)
901 if (atomic_read(&pd->iosched.attention) == 0)
903 atomic_set(&pd->iosched.attention, 0);
907 int reads_queued, writes_queued;
909 spin_lock(&pd->iosched.lock);
910 reads_queued = (pd->iosched.read_queue != NULL);
911 writes_queued = (pd->iosched.write_queue != NULL);
912 spin_unlock(&pd->iosched.lock);
914 if (!reads_queued && !writes_queued)
917 if (pd->iosched.writing) {
918 int need_write_seek = 1;
919 spin_lock(&pd->iosched.lock);
920 bio = pd->iosched.write_queue;
921 spin_unlock(&pd->iosched.lock);
922 if (bio && (bio->bi_sector == pd->iosched.last_write))
924 if (need_write_seek && reads_queued) {
925 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
926 VPRINTK(DRIVER_NAME": write, waiting\n");
930 pd->iosched.writing = 0;
933 if (!reads_queued && writes_queued) {
934 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
935 VPRINTK(DRIVER_NAME": read, waiting\n");
938 pd->iosched.writing = 1;
942 spin_lock(&pd->iosched.lock);
943 if (pd->iosched.writing) {
944 bio = pkt_get_list_first(&pd->iosched.write_queue,
945 &pd->iosched.write_queue_tail);
947 bio = pkt_get_list_first(&pd->iosched.read_queue,
948 &pd->iosched.read_queue_tail);
950 spin_unlock(&pd->iosched.lock);
955 if (bio_data_dir(bio) == READ)
956 pd->iosched.successive_reads += bio->bi_size >> 10;
958 pd->iosched.successive_reads = 0;
959 pd->iosched.last_write = bio->bi_sector + bio_sectors(bio);
961 if (pd->iosched.successive_reads >= HI_SPEED_SWITCH) {
962 if (pd->read_speed == pd->write_speed) {
963 pd->read_speed = MAX_SPEED;
964 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
967 if (pd->read_speed != pd->write_speed) {
968 pd->read_speed = pd->write_speed;
969 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
973 atomic_inc(&pd->cdrw.pending_bios);
974 generic_make_request(bio);
979 * Special care is needed if the underlying block device has a small
980 * max_phys_segments value.
982 static int pkt_set_segment_merging(struct pktcdvd_device *pd, struct request_queue *q)
984 if ((pd->settings.size << 9) / CD_FRAMESIZE <= q->max_phys_segments) {
986 * The cdrom device can handle one segment/frame
988 clear_bit(PACKET_MERGE_SEGS, &pd->flags);
990 } else if ((pd->settings.size << 9) / PAGE_SIZE <= q->max_phys_segments) {
992 * We can handle this case at the expense of some extra memory
993 * copies during write operations
995 set_bit(PACKET_MERGE_SEGS, &pd->flags);
998 printk(DRIVER_NAME": cdrom max_phys_segments too small\n");
1004 * Copy CD_FRAMESIZE bytes from src_bio into a destination page
1006 static void pkt_copy_bio_data(struct bio *src_bio, int seg, int offs, struct page *dst_page, int dst_offs)
1008 unsigned int copy_size = CD_FRAMESIZE;
1010 while (copy_size > 0) {
1011 struct bio_vec *src_bvl = bio_iovec_idx(src_bio, seg);
1012 void *vfrom = kmap_atomic(src_bvl->bv_page, KM_USER0) +
1013 src_bvl->bv_offset + offs;
1014 void *vto = page_address(dst_page) + dst_offs;
1015 int len = min_t(int, copy_size, src_bvl->bv_len - offs);
1018 memcpy(vto, vfrom, len);
1019 kunmap_atomic(vfrom, KM_USER0);
1029 * Copy all data for this packet to pkt->pages[], so that
1030 * a) The number of required segments for the write bio is minimized, which
1031 * is necessary for some scsi controllers.
1032 * b) The data can be used as cache to avoid read requests if we receive a
1033 * new write request for the same zone.
1035 static void pkt_make_local_copy(struct packet_data *pkt, struct bio_vec *bvec)
1039 /* Copy all data to pkt->pages[] */
1042 for (f = 0; f < pkt->frames; f++) {
1043 if (bvec[f].bv_page != pkt->pages[p]) {
1044 void *vfrom = kmap_atomic(bvec[f].bv_page, KM_USER0) + bvec[f].bv_offset;
1045 void *vto = page_address(pkt->pages[p]) + offs;
1046 memcpy(vto, vfrom, CD_FRAMESIZE);
1047 kunmap_atomic(vfrom, KM_USER0);
1048 bvec[f].bv_page = pkt->pages[p];
1049 bvec[f].bv_offset = offs;
1051 BUG_ON(bvec[f].bv_offset != offs);
1053 offs += CD_FRAMESIZE;
1054 if (offs >= PAGE_SIZE) {
1061 static void pkt_end_io_read(struct bio *bio, int err)
1063 struct packet_data *pkt = bio->bi_private;
1064 struct pktcdvd_device *pd = pkt->pd;
1067 VPRINTK("pkt_end_io_read: bio=%p sec0=%llx sec=%llx err=%d\n", bio,
1068 (unsigned long long)pkt->sector, (unsigned long long)bio->bi_sector, err);
1071 atomic_inc(&pkt->io_errors);
1072 if (atomic_dec_and_test(&pkt->io_wait)) {
1073 atomic_inc(&pkt->run_sm);
1074 wake_up(&pd->wqueue);
1076 pkt_bio_finished(pd);
1079 static void pkt_end_io_packet_write(struct bio *bio, int err)
1081 struct packet_data *pkt = bio->bi_private;
1082 struct pktcdvd_device *pd = pkt->pd;
1085 VPRINTK("pkt_end_io_packet_write: id=%d, err=%d\n", pkt->id, err);
1087 pd->stats.pkt_ended++;
1089 pkt_bio_finished(pd);
1090 atomic_dec(&pkt->io_wait);
1091 atomic_inc(&pkt->run_sm);
1092 wake_up(&pd->wqueue);
1096 * Schedule reads for the holes in a packet
1098 static void pkt_gather_data(struct pktcdvd_device *pd, struct packet_data *pkt)
1100 int frames_read = 0;
1103 char written[PACKET_MAX_SIZE];
1105 BUG_ON(!pkt->orig_bios);
1107 atomic_set(&pkt->io_wait, 0);
1108 atomic_set(&pkt->io_errors, 0);
1111 * Figure out which frames we need to read before we can write.
1113 memset(written, 0, sizeof(written));
1114 spin_lock(&pkt->lock);
1115 for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
1116 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
1117 int num_frames = bio->bi_size / CD_FRAMESIZE;
1118 pd->stats.secs_w += num_frames * (CD_FRAMESIZE >> 9);
1119 BUG_ON(first_frame < 0);
1120 BUG_ON(first_frame + num_frames > pkt->frames);
1121 for (f = first_frame; f < first_frame + num_frames; f++)
1124 spin_unlock(&pkt->lock);
1126 if (pkt->cache_valid) {
1127 VPRINTK("pkt_gather_data: zone %llx cached\n",
1128 (unsigned long long)pkt->sector);
1133 * Schedule reads for missing parts of the packet.
1135 for (f = 0; f < pkt->frames; f++) {
1139 bio = pkt->r_bios[f];
1141 bio->bi_max_vecs = 1;
1142 bio->bi_sector = pkt->sector + f * (CD_FRAMESIZE >> 9);
1143 bio->bi_bdev = pd->bdev;
1144 bio->bi_end_io = pkt_end_io_read;
1145 bio->bi_private = pkt;
1147 p = (f * CD_FRAMESIZE) / PAGE_SIZE;
1148 offset = (f * CD_FRAMESIZE) % PAGE_SIZE;
1149 VPRINTK("pkt_gather_data: Adding frame %d, page:%p offs:%d\n",
1150 f, pkt->pages[p], offset);
1151 if (!bio_add_page(bio, pkt->pages[p], CD_FRAMESIZE, offset))
1154 atomic_inc(&pkt->io_wait);
1156 pkt_queue_bio(pd, bio);
1161 VPRINTK("pkt_gather_data: need %d frames for zone %llx\n",
1162 frames_read, (unsigned long long)pkt->sector);
1163 pd->stats.pkt_started++;
1164 pd->stats.secs_rg += frames_read * (CD_FRAMESIZE >> 9);
1168 * Find a packet matching zone, or the least recently used packet if
1169 * there is no match.
1171 static struct packet_data *pkt_get_packet_data(struct pktcdvd_device *pd, int zone)
1173 struct packet_data *pkt;
1175 list_for_each_entry(pkt, &pd->cdrw.pkt_free_list, list) {
1176 if (pkt->sector == zone || pkt->list.next == &pd->cdrw.pkt_free_list) {
1177 list_del_init(&pkt->list);
1178 if (pkt->sector != zone)
1179 pkt->cache_valid = 0;
1187 static void pkt_put_packet_data(struct pktcdvd_device *pd, struct packet_data *pkt)
1189 if (pkt->cache_valid) {
1190 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
1192 list_add_tail(&pkt->list, &pd->cdrw.pkt_free_list);
1197 * recover a failed write, query for relocation if possible
1199 * returns 1 if recovery is possible, or 0 if not
1202 static int pkt_start_recovery(struct packet_data *pkt)
1205 * FIXME. We need help from the file system to implement
1206 * recovery handling.
1210 struct request *rq = pkt->rq;
1211 struct pktcdvd_device *pd = rq->rq_disk->private_data;
1212 struct block_device *pkt_bdev;
1213 struct super_block *sb = NULL;
1214 unsigned long old_block, new_block;
1215 sector_t new_sector;
1217 pkt_bdev = bdget(kdev_t_to_nr(pd->pkt_dev));
1219 sb = get_super(pkt_bdev);
1226 if (!sb->s_op || !sb->s_op->relocate_blocks)
1229 old_block = pkt->sector / (CD_FRAMESIZE >> 9);
1230 if (sb->s_op->relocate_blocks(sb, old_block, &new_block))
1233 new_sector = new_block * (CD_FRAMESIZE >> 9);
1234 pkt->sector = new_sector;
1236 pkt->bio->bi_sector = new_sector;
1237 pkt->bio->bi_next = NULL;
1238 pkt->bio->bi_flags = 1 << BIO_UPTODATE;
1239 pkt->bio->bi_idx = 0;
1241 BUG_ON(pkt->bio->bi_rw != (1 << BIO_RW));
1242 BUG_ON(pkt->bio->bi_vcnt != pkt->frames);
1243 BUG_ON(pkt->bio->bi_size != pkt->frames * CD_FRAMESIZE);
1244 BUG_ON(pkt->bio->bi_end_io != pkt_end_io_packet_write);
1245 BUG_ON(pkt->bio->bi_private != pkt);
1256 static inline void pkt_set_state(struct packet_data *pkt, enum packet_data_state state)
1258 #if PACKET_DEBUG > 1
1259 static const char *state_name[] = {
1260 "IDLE", "WAITING", "READ_WAIT", "WRITE_WAIT", "RECOVERY", "FINISHED"
1262 enum packet_data_state old_state = pkt->state;
1263 VPRINTK("pkt %2d : s=%6llx %s -> %s\n", pkt->id, (unsigned long long)pkt->sector,
1264 state_name[old_state], state_name[state]);
1270 * Scan the work queue to see if we can start a new packet.
1271 * returns non-zero if any work was done.
1273 static int pkt_handle_queue(struct pktcdvd_device *pd)
1275 struct packet_data *pkt, *p;
1276 struct bio *bio = NULL;
1277 sector_t zone = 0; /* Suppress gcc warning */
1278 struct pkt_rb_node *node, *first_node;
1282 VPRINTK("handle_queue\n");
1284 atomic_set(&pd->scan_queue, 0);
1286 if (list_empty(&pd->cdrw.pkt_free_list)) {
1287 VPRINTK("handle_queue: no pkt\n");
1292 * Try to find a zone we are not already working on.
1294 spin_lock(&pd->lock);
1295 first_node = pkt_rbtree_find(pd, pd->current_sector);
1297 n = rb_first(&pd->bio_queue);
1299 first_node = rb_entry(n, struct pkt_rb_node, rb_node);
1304 zone = ZONE(bio->bi_sector, pd);
1305 list_for_each_entry(p, &pd->cdrw.pkt_active_list, list) {
1306 if (p->sector == zone) {
1313 node = pkt_rbtree_next(node);
1315 n = rb_first(&pd->bio_queue);
1317 node = rb_entry(n, struct pkt_rb_node, rb_node);
1319 if (node == first_node)
1322 spin_unlock(&pd->lock);
1324 VPRINTK("handle_queue: no bio\n");
1328 pkt = pkt_get_packet_data(pd, zone);
1330 pd->current_sector = zone + pd->settings.size;
1332 BUG_ON(pkt->frames != pd->settings.size >> 2);
1333 pkt->write_size = 0;
1336 * Scan work queue for bios in the same zone and link them
1339 spin_lock(&pd->lock);
1340 VPRINTK("pkt_handle_queue: looking for zone %llx\n", (unsigned long long)zone);
1341 while ((node = pkt_rbtree_find(pd, zone)) != NULL) {
1343 VPRINTK("pkt_handle_queue: found zone=%llx\n",
1344 (unsigned long long)ZONE(bio->bi_sector, pd));
1345 if (ZONE(bio->bi_sector, pd) != zone)
1347 pkt_rbtree_erase(pd, node);
1348 spin_lock(&pkt->lock);
1349 pkt_add_list_last(bio, &pkt->orig_bios, &pkt->orig_bios_tail);
1350 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
1351 spin_unlock(&pkt->lock);
1353 /* check write congestion marks, and if bio_queue_size is
1354 below, wake up any waiters */
1355 wakeup = (pd->write_congestion_on > 0
1356 && pd->bio_queue_size <= pd->write_congestion_off);
1357 spin_unlock(&pd->lock);
1359 clear_bdi_congested(&pd->disk->queue->backing_dev_info, WRITE);
1361 pkt->sleep_time = max(PACKET_WAIT_TIME, 1);
1362 pkt_set_state(pkt, PACKET_WAITING_STATE);
1363 atomic_set(&pkt->run_sm, 1);
1365 spin_lock(&pd->cdrw.active_list_lock);
1366 list_add(&pkt->list, &pd->cdrw.pkt_active_list);
1367 spin_unlock(&pd->cdrw.active_list_lock);
1373 * Assemble a bio to write one packet and queue the bio for processing
1374 * by the underlying block device.
1376 static void pkt_start_write(struct pktcdvd_device *pd, struct packet_data *pkt)
1381 struct bio_vec *bvec = pkt->w_bio->bi_io_vec;
1383 for (f = 0; f < pkt->frames; f++) {
1384 bvec[f].bv_page = pkt->pages[(f * CD_FRAMESIZE) / PAGE_SIZE];
1385 bvec[f].bv_offset = (f * CD_FRAMESIZE) % PAGE_SIZE;
1389 * Fill-in bvec with data from orig_bios.
1392 spin_lock(&pkt->lock);
1393 for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
1394 int segment = bio->bi_idx;
1396 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
1397 int num_frames = bio->bi_size / CD_FRAMESIZE;
1398 BUG_ON(first_frame < 0);
1399 BUG_ON(first_frame + num_frames > pkt->frames);
1400 for (f = first_frame; f < first_frame + num_frames; f++) {
1401 struct bio_vec *src_bvl = bio_iovec_idx(bio, segment);
1403 while (src_offs >= src_bvl->bv_len) {
1404 src_offs -= src_bvl->bv_len;
1406 BUG_ON(segment >= bio->bi_vcnt);
1407 src_bvl = bio_iovec_idx(bio, segment);
1410 if (src_bvl->bv_len - src_offs >= CD_FRAMESIZE) {
1411 bvec[f].bv_page = src_bvl->bv_page;
1412 bvec[f].bv_offset = src_bvl->bv_offset + src_offs;
1414 pkt_copy_bio_data(bio, segment, src_offs,
1415 bvec[f].bv_page, bvec[f].bv_offset);
1417 src_offs += CD_FRAMESIZE;
1421 pkt_set_state(pkt, PACKET_WRITE_WAIT_STATE);
1422 spin_unlock(&pkt->lock);
1424 VPRINTK("pkt_start_write: Writing %d frames for zone %llx\n",
1425 frames_write, (unsigned long long)pkt->sector);
1426 BUG_ON(frames_write != pkt->write_size);
1428 if (test_bit(PACKET_MERGE_SEGS, &pd->flags) || (pkt->write_size < pkt->frames)) {
1429 pkt_make_local_copy(pkt, bvec);
1430 pkt->cache_valid = 1;
1432 pkt->cache_valid = 0;
1435 /* Start the write request */
1436 bio_init(pkt->w_bio);
1437 pkt->w_bio->bi_max_vecs = PACKET_MAX_SIZE;
1438 pkt->w_bio->bi_sector = pkt->sector;
1439 pkt->w_bio->bi_bdev = pd->bdev;
1440 pkt->w_bio->bi_end_io = pkt_end_io_packet_write;
1441 pkt->w_bio->bi_private = pkt;
1442 for (f = 0; f < pkt->frames; f++)
1443 if (!bio_add_page(pkt->w_bio, bvec[f].bv_page, CD_FRAMESIZE, bvec[f].bv_offset))
1445 VPRINTK(DRIVER_NAME": vcnt=%d\n", pkt->w_bio->bi_vcnt);
1447 atomic_set(&pkt->io_wait, 1);
1448 pkt->w_bio->bi_rw = WRITE;
1449 pkt_queue_bio(pd, pkt->w_bio);
1452 static void pkt_finish_packet(struct packet_data *pkt, int uptodate)
1454 struct bio *bio, *next;
1457 pkt->cache_valid = 0;
1459 /* Finish all bios corresponding to this packet */
1460 bio = pkt->orig_bios;
1462 next = bio->bi_next;
1463 bio->bi_next = NULL;
1464 bio_endio(bio, uptodate ? 0 : -EIO);
1467 pkt->orig_bios = pkt->orig_bios_tail = NULL;
1470 static void pkt_run_state_machine(struct pktcdvd_device *pd, struct packet_data *pkt)
1474 VPRINTK("run_state_machine: pkt %d\n", pkt->id);
1477 switch (pkt->state) {
1478 case PACKET_WAITING_STATE:
1479 if ((pkt->write_size < pkt->frames) && (pkt->sleep_time > 0))
1482 pkt->sleep_time = 0;
1483 pkt_gather_data(pd, pkt);
1484 pkt_set_state(pkt, PACKET_READ_WAIT_STATE);
1487 case PACKET_READ_WAIT_STATE:
1488 if (atomic_read(&pkt->io_wait) > 0)
1491 if (atomic_read(&pkt->io_errors) > 0) {
1492 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1494 pkt_start_write(pd, pkt);
1498 case PACKET_WRITE_WAIT_STATE:
1499 if (atomic_read(&pkt->io_wait) > 0)
1502 if (test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags)) {
1503 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1505 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1509 case PACKET_RECOVERY_STATE:
1510 if (pkt_start_recovery(pkt)) {
1511 pkt_start_write(pd, pkt);
1513 VPRINTK("No recovery possible\n");
1514 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1518 case PACKET_FINISHED_STATE:
1519 uptodate = test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags);
1520 pkt_finish_packet(pkt, uptodate);
1530 static void pkt_handle_packets(struct pktcdvd_device *pd)
1532 struct packet_data *pkt, *next;
1534 VPRINTK("pkt_handle_packets\n");
1537 * Run state machine for active packets
1539 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1540 if (atomic_read(&pkt->run_sm) > 0) {
1541 atomic_set(&pkt->run_sm, 0);
1542 pkt_run_state_machine(pd, pkt);
1547 * Move no longer active packets to the free list
1549 spin_lock(&pd->cdrw.active_list_lock);
1550 list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_active_list, list) {
1551 if (pkt->state == PACKET_FINISHED_STATE) {
1552 list_del(&pkt->list);
1553 pkt_put_packet_data(pd, pkt);
1554 pkt_set_state(pkt, PACKET_IDLE_STATE);
1555 atomic_set(&pd->scan_queue, 1);
1558 spin_unlock(&pd->cdrw.active_list_lock);
1561 static void pkt_count_states(struct pktcdvd_device *pd, int *states)
1563 struct packet_data *pkt;
1566 for (i = 0; i < PACKET_NUM_STATES; i++)
1569 spin_lock(&pd->cdrw.active_list_lock);
1570 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1571 states[pkt->state]++;
1573 spin_unlock(&pd->cdrw.active_list_lock);
1577 * kcdrwd is woken up when writes have been queued for one of our
1578 * registered devices
1580 static int kcdrwd(void *foobar)
1582 struct pktcdvd_device *pd = foobar;
1583 struct packet_data *pkt;
1584 long min_sleep_time, residue;
1586 set_user_nice(current, -20);
1590 DECLARE_WAITQUEUE(wait, current);
1593 * Wait until there is something to do
1595 add_wait_queue(&pd->wqueue, &wait);
1597 set_current_state(TASK_INTERRUPTIBLE);
1599 /* Check if we need to run pkt_handle_queue */
1600 if (atomic_read(&pd->scan_queue) > 0)
1603 /* Check if we need to run the state machine for some packet */
1604 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1605 if (atomic_read(&pkt->run_sm) > 0)
1609 /* Check if we need to process the iosched queues */
1610 if (atomic_read(&pd->iosched.attention) != 0)
1613 /* Otherwise, go to sleep */
1614 if (PACKET_DEBUG > 1) {
1615 int states[PACKET_NUM_STATES];
1616 pkt_count_states(pd, states);
1617 VPRINTK("kcdrwd: i:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
1618 states[0], states[1], states[2], states[3],
1619 states[4], states[5]);
1622 min_sleep_time = MAX_SCHEDULE_TIMEOUT;
1623 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1624 if (pkt->sleep_time && pkt->sleep_time < min_sleep_time)
1625 min_sleep_time = pkt->sleep_time;
1628 generic_unplug_device(bdev_get_queue(pd->bdev));
1630 VPRINTK("kcdrwd: sleeping\n");
1631 residue = schedule_timeout(min_sleep_time);
1632 VPRINTK("kcdrwd: wake up\n");
1634 /* make swsusp happy with our thread */
1637 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1638 if (!pkt->sleep_time)
1640 pkt->sleep_time -= min_sleep_time - residue;
1641 if (pkt->sleep_time <= 0) {
1642 pkt->sleep_time = 0;
1643 atomic_inc(&pkt->run_sm);
1647 if (kthread_should_stop())
1651 set_current_state(TASK_RUNNING);
1652 remove_wait_queue(&pd->wqueue, &wait);
1654 if (kthread_should_stop())
1658 * if pkt_handle_queue returns true, we can queue
1661 while (pkt_handle_queue(pd))
1665 * Handle packet state machine
1667 pkt_handle_packets(pd);
1670 * Handle iosched queues
1672 pkt_iosched_process_queue(pd);
1678 static void pkt_print_settings(struct pktcdvd_device *pd)
1680 printk(DRIVER_NAME": %s packets, ", pd->settings.fp ? "Fixed" : "Variable");
1681 printk("%u blocks, ", pd->settings.size >> 2);
1682 printk("Mode-%c disc\n", pd->settings.block_mode == 8 ? '1' : '2');
1685 static int pkt_mode_sense(struct pktcdvd_device *pd, struct packet_command *cgc, int page_code, int page_control)
1687 memset(cgc->cmd, 0, sizeof(cgc->cmd));
1689 cgc->cmd[0] = GPCMD_MODE_SENSE_10;
1690 cgc->cmd[2] = page_code | (page_control << 6);
1691 cgc->cmd[7] = cgc->buflen >> 8;
1692 cgc->cmd[8] = cgc->buflen & 0xff;
1693 cgc->data_direction = CGC_DATA_READ;
1694 return pkt_generic_packet(pd, cgc);
1697 static int pkt_mode_select(struct pktcdvd_device *pd, struct packet_command *cgc)
1699 memset(cgc->cmd, 0, sizeof(cgc->cmd));
1700 memset(cgc->buffer, 0, 2);
1701 cgc->cmd[0] = GPCMD_MODE_SELECT_10;
1702 cgc->cmd[1] = 0x10; /* PF */
1703 cgc->cmd[7] = cgc->buflen >> 8;
1704 cgc->cmd[8] = cgc->buflen & 0xff;
1705 cgc->data_direction = CGC_DATA_WRITE;
1706 return pkt_generic_packet(pd, cgc);
1709 static int pkt_get_disc_info(struct pktcdvd_device *pd, disc_information *di)
1711 struct packet_command cgc;
1714 /* set up command and get the disc info */
1715 init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);
1716 cgc.cmd[0] = GPCMD_READ_DISC_INFO;
1717 cgc.cmd[8] = cgc.buflen = 2;
1720 if ((ret = pkt_generic_packet(pd, &cgc)))
1723 /* not all drives have the same disc_info length, so requeue
1724 * packet with the length the drive tells us it can supply
1726 cgc.buflen = be16_to_cpu(di->disc_information_length) +
1727 sizeof(di->disc_information_length);
1729 if (cgc.buflen > sizeof(disc_information))
1730 cgc.buflen = sizeof(disc_information);
1732 cgc.cmd[8] = cgc.buflen;
1733 return pkt_generic_packet(pd, &cgc);
1736 static int pkt_get_track_info(struct pktcdvd_device *pd, __u16 track, __u8 type, track_information *ti)
1738 struct packet_command cgc;
1741 init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);
1742 cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;
1743 cgc.cmd[1] = type & 3;
1744 cgc.cmd[4] = (track & 0xff00) >> 8;
1745 cgc.cmd[5] = track & 0xff;
1749 if ((ret = pkt_generic_packet(pd, &cgc)))
1752 cgc.buflen = be16_to_cpu(ti->track_information_length) +
1753 sizeof(ti->track_information_length);
1755 if (cgc.buflen > sizeof(track_information))
1756 cgc.buflen = sizeof(track_information);
1758 cgc.cmd[8] = cgc.buflen;
1759 return pkt_generic_packet(pd, &cgc);
1762 static int pkt_get_last_written(struct pktcdvd_device *pd, long *last_written)
1764 disc_information di;
1765 track_information ti;
1769 if ((ret = pkt_get_disc_info(pd, &di)))
1772 last_track = (di.last_track_msb << 8) | di.last_track_lsb;
1773 if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1776 /* if this track is blank, try the previous. */
1779 if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1783 /* if last recorded field is valid, return it. */
1785 *last_written = be32_to_cpu(ti.last_rec_address);
1787 /* make it up instead */
1788 *last_written = be32_to_cpu(ti.track_start) +
1789 be32_to_cpu(ti.track_size);
1791 *last_written -= (be32_to_cpu(ti.free_blocks) + 7);
1797 * write mode select package based on pd->settings
1799 static int pkt_set_write_settings(struct pktcdvd_device *pd)
1801 struct packet_command cgc;
1802 struct request_sense sense;
1803 write_param_page *wp;
1807 /* doesn't apply to DVD+RW or DVD-RAM */
1808 if ((pd->mmc3_profile == 0x1a) || (pd->mmc3_profile == 0x12))
1811 memset(buffer, 0, sizeof(buffer));
1812 init_cdrom_command(&cgc, buffer, sizeof(*wp), CGC_DATA_READ);
1814 if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1815 pkt_dump_sense(&cgc);
1819 size = 2 + ((buffer[0] << 8) | (buffer[1] & 0xff));
1820 pd->mode_offset = (buffer[6] << 8) | (buffer[7] & 0xff);
1821 if (size > sizeof(buffer))
1822 size = sizeof(buffer);
1827 init_cdrom_command(&cgc, buffer, size, CGC_DATA_READ);
1829 if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1830 pkt_dump_sense(&cgc);
1835 * write page is offset header + block descriptor length
1837 wp = (write_param_page *) &buffer[sizeof(struct mode_page_header) + pd->mode_offset];
1839 wp->fp = pd->settings.fp;
1840 wp->track_mode = pd->settings.track_mode;
1841 wp->write_type = pd->settings.write_type;
1842 wp->data_block_type = pd->settings.block_mode;
1844 wp->multi_session = 0;
1846 #ifdef PACKET_USE_LS
1851 if (wp->data_block_type == PACKET_BLOCK_MODE1) {
1852 wp->session_format = 0;
1854 } else if (wp->data_block_type == PACKET_BLOCK_MODE2) {
1855 wp->session_format = 0x20;
1859 memcpy(&wp->mcn[1], PACKET_MCN, sizeof(wp->mcn) - 1);
1865 printk(DRIVER_NAME": write mode wrong %d\n", wp->data_block_type);
1868 wp->packet_size = cpu_to_be32(pd->settings.size >> 2);
1870 cgc.buflen = cgc.cmd[8] = size;
1871 if ((ret = pkt_mode_select(pd, &cgc))) {
1872 pkt_dump_sense(&cgc);
1876 pkt_print_settings(pd);
1881 * 1 -- we can write to this track, 0 -- we can't
1883 static int pkt_writable_track(struct pktcdvd_device *pd, track_information *ti)
1885 switch (pd->mmc3_profile) {
1886 case 0x1a: /* DVD+RW */
1887 case 0x12: /* DVD-RAM */
1888 /* The track is always writable on DVD+RW/DVD-RAM */
1894 if (!ti->packet || !ti->fp)
1898 * "good" settings as per Mt Fuji.
1900 if (ti->rt == 0 && ti->blank == 0)
1903 if (ti->rt == 0 && ti->blank == 1)
1906 if (ti->rt == 1 && ti->blank == 0)
1909 printk(DRIVER_NAME": bad state %d-%d-%d\n", ti->rt, ti->blank, ti->packet);
1914 * 1 -- we can write to this disc, 0 -- we can't
1916 static int pkt_writable_disc(struct pktcdvd_device *pd, disc_information *di)
1918 switch (pd->mmc3_profile) {
1919 case 0x0a: /* CD-RW */
1920 case 0xffff: /* MMC3 not supported */
1922 case 0x1a: /* DVD+RW */
1923 case 0x13: /* DVD-RW */
1924 case 0x12: /* DVD-RAM */
1927 VPRINTK(DRIVER_NAME": Wrong disc profile (%x)\n", pd->mmc3_profile);
1932 * for disc type 0xff we should probably reserve a new track.
1933 * but i'm not sure, should we leave this to user apps? probably.
1935 if (di->disc_type == 0xff) {
1936 printk(DRIVER_NAME": Unknown disc. No track?\n");
1940 if (di->disc_type != 0x20 && di->disc_type != 0) {
1941 printk(DRIVER_NAME": Wrong disc type (%x)\n", di->disc_type);
1945 if (di->erasable == 0) {
1946 printk(DRIVER_NAME": Disc not erasable\n");
1950 if (di->border_status == PACKET_SESSION_RESERVED) {
1951 printk(DRIVER_NAME": Can't write to last track (reserved)\n");
1958 static int pkt_probe_settings(struct pktcdvd_device *pd)
1960 struct packet_command cgc;
1961 unsigned char buf[12];
1962 disc_information di;
1963 track_information ti;
1966 init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1967 cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
1969 ret = pkt_generic_packet(pd, &cgc);
1970 pd->mmc3_profile = ret ? 0xffff : buf[6] << 8 | buf[7];
1972 memset(&di, 0, sizeof(disc_information));
1973 memset(&ti, 0, sizeof(track_information));
1975 if ((ret = pkt_get_disc_info(pd, &di))) {
1976 printk("failed get_disc\n");
1980 if (!pkt_writable_disc(pd, &di))
1983 pd->type = di.erasable ? PACKET_CDRW : PACKET_CDR;
1985 track = 1; /* (di.last_track_msb << 8) | di.last_track_lsb; */
1986 if ((ret = pkt_get_track_info(pd, track, 1, &ti))) {
1987 printk(DRIVER_NAME": failed get_track\n");
1991 if (!pkt_writable_track(pd, &ti)) {
1992 printk(DRIVER_NAME": can't write to this track\n");
1997 * we keep packet size in 512 byte units, makes it easier to
1998 * deal with request calculations.
2000 pd->settings.size = be32_to_cpu(ti.fixed_packet_size) << 2;
2001 if (pd->settings.size == 0) {
2002 printk(DRIVER_NAME": detected zero packet size!\n");
2005 if (pd->settings.size > PACKET_MAX_SECTORS) {
2006 printk(DRIVER_NAME": packet size is too big\n");
2009 pd->settings.fp = ti.fp;
2010 pd->offset = (be32_to_cpu(ti.track_start) << 2) & (pd->settings.size - 1);
2013 pd->nwa = be32_to_cpu(ti.next_writable);
2014 set_bit(PACKET_NWA_VALID, &pd->flags);
2018 * in theory we could use lra on -RW media as well and just zero
2019 * blocks that haven't been written yet, but in practice that
2020 * is just a no-go. we'll use that for -R, naturally.
2023 pd->lra = be32_to_cpu(ti.last_rec_address);
2024 set_bit(PACKET_LRA_VALID, &pd->flags);
2026 pd->lra = 0xffffffff;
2027 set_bit(PACKET_LRA_VALID, &pd->flags);
2033 pd->settings.link_loss = 7;
2034 pd->settings.write_type = 0; /* packet */
2035 pd->settings.track_mode = ti.track_mode;
2038 * mode1 or mode2 disc
2040 switch (ti.data_mode) {
2042 pd->settings.block_mode = PACKET_BLOCK_MODE1;
2045 pd->settings.block_mode = PACKET_BLOCK_MODE2;
2048 printk(DRIVER_NAME": unknown data mode\n");
2055 * enable/disable write caching on drive
2057 static int pkt_write_caching(struct pktcdvd_device *pd, int set)
2059 struct packet_command cgc;
2060 struct request_sense sense;
2061 unsigned char buf[64];
2064 memset(buf, 0, sizeof(buf));
2065 init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
2067 cgc.buflen = pd->mode_offset + 12;
2070 * caching mode page might not be there, so quiet this command
2074 if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WCACHING_PAGE, 0)))
2077 buf[pd->mode_offset + 10] |= (!!set << 2);
2079 cgc.buflen = cgc.cmd[8] = 2 + ((buf[0] << 8) | (buf[1] & 0xff));
2080 ret = pkt_mode_select(pd, &cgc);
2082 printk(DRIVER_NAME": write caching control failed\n");
2083 pkt_dump_sense(&cgc);
2084 } else if (!ret && set)
2085 printk(DRIVER_NAME": enabled write caching on %s\n", pd->name);
2089 static int pkt_lock_door(struct pktcdvd_device *pd, int lockflag)
2091 struct packet_command cgc;
2093 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
2094 cgc.cmd[0] = GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL;
2095 cgc.cmd[4] = lockflag ? 1 : 0;
2096 return pkt_generic_packet(pd, &cgc);
2100 * Returns drive maximum write speed
2102 static int pkt_get_max_speed(struct pktcdvd_device *pd, unsigned *write_speed)
2104 struct packet_command cgc;
2105 struct request_sense sense;
2106 unsigned char buf[256+18];
2107 unsigned char *cap_buf;
2110 memset(buf, 0, sizeof(buf));
2111 cap_buf = &buf[sizeof(struct mode_page_header) + pd->mode_offset];
2112 init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_UNKNOWN);
2115 ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
2117 cgc.buflen = pd->mode_offset + cap_buf[1] + 2 +
2118 sizeof(struct mode_page_header);
2119 ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
2121 pkt_dump_sense(&cgc);
2126 offset = 20; /* Obsoleted field, used by older drives */
2127 if (cap_buf[1] >= 28)
2128 offset = 28; /* Current write speed selected */
2129 if (cap_buf[1] >= 30) {
2130 /* If the drive reports at least one "Logical Unit Write
2131 * Speed Performance Descriptor Block", use the information
2132 * in the first block. (contains the highest speed)
2134 int num_spdb = (cap_buf[30] << 8) + cap_buf[31];
2139 *write_speed = (cap_buf[offset] << 8) | cap_buf[offset + 1];
2143 /* These tables from cdrecord - I don't have orange book */
2144 /* standard speed CD-RW (1-4x) */
2145 static char clv_to_speed[16] = {
2146 /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
2147 0, 2, 4, 6, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
2149 /* high speed CD-RW (-10x) */
2150 static char hs_clv_to_speed[16] = {
2151 /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
2152 0, 2, 4, 6, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
2154 /* ultra high speed CD-RW */
2155 static char us_clv_to_speed[16] = {
2156 /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
2157 0, 2, 4, 8, 0, 0,16, 0,24,32,40,48, 0, 0, 0, 0
2161 * reads the maximum media speed from ATIP
2163 static int pkt_media_speed(struct pktcdvd_device *pd, unsigned *speed)
2165 struct packet_command cgc;
2166 struct request_sense sense;
2167 unsigned char buf[64];
2168 unsigned int size, st, sp;
2171 init_cdrom_command(&cgc, buf, 2, CGC_DATA_READ);
2173 cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
2175 cgc.cmd[2] = 4; /* READ ATIP */
2177 ret = pkt_generic_packet(pd, &cgc);
2179 pkt_dump_sense(&cgc);
2182 size = ((unsigned int) buf[0]<<8) + buf[1] + 2;
2183 if (size > sizeof(buf))
2186 init_cdrom_command(&cgc, buf, size, CGC_DATA_READ);
2188 cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
2192 ret = pkt_generic_packet(pd, &cgc);
2194 pkt_dump_sense(&cgc);
2198 if (!buf[6] & 0x40) {
2199 printk(DRIVER_NAME": Disc type is not CD-RW\n");
2202 if (!buf[6] & 0x4) {
2203 printk(DRIVER_NAME": A1 values on media are not valid, maybe not CDRW?\n");
2207 st = (buf[6] >> 3) & 0x7; /* disc sub-type */
2209 sp = buf[16] & 0xf; /* max speed from ATIP A1 field */
2211 /* Info from cdrecord */
2213 case 0: /* standard speed */
2214 *speed = clv_to_speed[sp];
2216 case 1: /* high speed */
2217 *speed = hs_clv_to_speed[sp];
2219 case 2: /* ultra high speed */
2220 *speed = us_clv_to_speed[sp];
2223 printk(DRIVER_NAME": Unknown disc sub-type %d\n",st);
2227 printk(DRIVER_NAME": Max. media speed: %d\n",*speed);
2230 printk(DRIVER_NAME": Unknown speed %d for sub-type %d\n",sp,st);
2235 static int pkt_perform_opc(struct pktcdvd_device *pd)
2237 struct packet_command cgc;
2238 struct request_sense sense;
2241 VPRINTK(DRIVER_NAME": Performing OPC\n");
2243 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
2245 cgc.timeout = 60*HZ;
2246 cgc.cmd[0] = GPCMD_SEND_OPC;
2248 if ((ret = pkt_generic_packet(pd, &cgc)))
2249 pkt_dump_sense(&cgc);
2253 static int pkt_open_write(struct pktcdvd_device *pd)
2256 unsigned int write_speed, media_write_speed, read_speed;
2258 if ((ret = pkt_probe_settings(pd))) {
2259 VPRINTK(DRIVER_NAME": %s failed probe\n", pd->name);
2263 if ((ret = pkt_set_write_settings(pd))) {
2264 DPRINTK(DRIVER_NAME": %s failed saving write settings\n", pd->name);
2268 pkt_write_caching(pd, USE_WCACHING);
2270 if ((ret = pkt_get_max_speed(pd, &write_speed)))
2271 write_speed = 16 * 177;
2272 switch (pd->mmc3_profile) {
2273 case 0x13: /* DVD-RW */
2274 case 0x1a: /* DVD+RW */
2275 case 0x12: /* DVD-RAM */
2276 DPRINTK(DRIVER_NAME": write speed %ukB/s\n", write_speed);
2279 if ((ret = pkt_media_speed(pd, &media_write_speed)))
2280 media_write_speed = 16;
2281 write_speed = min(write_speed, media_write_speed * 177);
2282 DPRINTK(DRIVER_NAME": write speed %ux\n", write_speed / 176);
2285 read_speed = write_speed;
2287 if ((ret = pkt_set_speed(pd, write_speed, read_speed))) {
2288 DPRINTK(DRIVER_NAME": %s couldn't set write speed\n", pd->name);
2291 pd->write_speed = write_speed;
2292 pd->read_speed = read_speed;
2294 if ((ret = pkt_perform_opc(pd))) {
2295 DPRINTK(DRIVER_NAME": %s Optimum Power Calibration failed\n", pd->name);
2302 * called at open time.
2304 static int pkt_open_dev(struct pktcdvd_device *pd, int write)
2308 struct request_queue *q;
2311 * We need to re-open the cdrom device without O_NONBLOCK to be able
2312 * to read/write from/to it. It is already opened in O_NONBLOCK mode
2313 * so bdget() can't fail.
2315 bdget(pd->bdev->bd_dev);
2316 if ((ret = blkdev_get(pd->bdev, FMODE_READ, O_RDONLY)))
2319 if ((ret = bd_claim(pd->bdev, pd)))
2322 if ((ret = pkt_get_last_written(pd, &lba))) {
2323 printk(DRIVER_NAME": pkt_get_last_written failed\n");
2327 set_capacity(pd->disk, lba << 2);
2328 set_capacity(pd->bdev->bd_disk, lba << 2);
2329 bd_set_size(pd->bdev, (loff_t)lba << 11);
2331 q = bdev_get_queue(pd->bdev);
2333 if ((ret = pkt_open_write(pd)))
2336 * Some CDRW drives can not handle writes larger than one packet,
2337 * even if the size is a multiple of the packet size.
2339 spin_lock_irq(q->queue_lock);
2340 blk_queue_max_sectors(q, pd->settings.size);
2341 spin_unlock_irq(q->queue_lock);
2342 set_bit(PACKET_WRITABLE, &pd->flags);
2344 pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
2345 clear_bit(PACKET_WRITABLE, &pd->flags);
2348 if ((ret = pkt_set_segment_merging(pd, q)))
2352 if (!pkt_grow_pktlist(pd, CONFIG_CDROM_PKTCDVD_BUFFERS)) {
2353 printk(DRIVER_NAME": not enough memory for buffers\n");
2357 printk(DRIVER_NAME": %lukB available on disc\n", lba << 1);
2363 bd_release(pd->bdev);
2365 blkdev_put(pd->bdev);
2371 * called when the device is closed. makes sure that the device flushes
2372 * the internal cache before we close.
2374 static void pkt_release_dev(struct pktcdvd_device *pd, int flush)
2376 if (flush && pkt_flush_cache(pd))
2377 DPRINTK(DRIVER_NAME": %s not flushing cache\n", pd->name);
2379 pkt_lock_door(pd, 0);
2381 pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
2382 bd_release(pd->bdev);
2383 blkdev_put(pd->bdev);
2385 pkt_shrink_pktlist(pd);
2388 static struct pktcdvd_device *pkt_find_dev_from_minor(int dev_minor)
2390 if (dev_minor >= MAX_WRITERS)
2392 return pkt_devs[dev_minor];
2395 static int pkt_open(struct inode *inode, struct file *file)
2397 struct pktcdvd_device *pd = NULL;
2400 VPRINTK(DRIVER_NAME": entering open\n");
2402 mutex_lock(&ctl_mutex);
2403 pd = pkt_find_dev_from_minor(iminor(inode));
2408 BUG_ON(pd->refcnt < 0);
2411 if (pd->refcnt > 1) {
2412 if ((file->f_mode & FMODE_WRITE) &&
2413 !test_bit(PACKET_WRITABLE, &pd->flags)) {
2418 ret = pkt_open_dev(pd, file->f_mode & FMODE_WRITE);
2422 * needed here as well, since ext2 (among others) may change
2423 * the blocksize at mount time
2425 set_blocksize(inode->i_bdev, CD_FRAMESIZE);
2428 mutex_unlock(&ctl_mutex);
2434 VPRINTK(DRIVER_NAME": failed open (%d)\n", ret);
2435 mutex_unlock(&ctl_mutex);
2439 static int pkt_close(struct inode *inode, struct file *file)
2441 struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2444 mutex_lock(&ctl_mutex);
2446 BUG_ON(pd->refcnt < 0);
2447 if (pd->refcnt == 0) {
2448 int flush = test_bit(PACKET_WRITABLE, &pd->flags);
2449 pkt_release_dev(pd, flush);
2451 mutex_unlock(&ctl_mutex);
2456 static void pkt_end_io_read_cloned(struct bio *bio, int err)
2458 struct packet_stacked_data *psd = bio->bi_private;
2459 struct pktcdvd_device *pd = psd->pd;
2462 bio_endio(psd->bio, err);
2463 mempool_free(psd, psd_pool);
2464 pkt_bio_finished(pd);
2467 static int pkt_make_request(struct request_queue *q, struct bio *bio)
2469 struct pktcdvd_device *pd;
2470 char b[BDEVNAME_SIZE];
2472 struct packet_data *pkt;
2473 int was_empty, blocked_bio;
2474 struct pkt_rb_node *node;
2478 printk(DRIVER_NAME": %s incorrect request queue\n", bdevname(bio->bi_bdev, b));
2483 * Clone READ bios so we can have our own bi_end_io callback.
2485 if (bio_data_dir(bio) == READ) {
2486 struct bio *cloned_bio = bio_clone(bio, GFP_NOIO);
2487 struct packet_stacked_data *psd = mempool_alloc(psd_pool, GFP_NOIO);
2491 cloned_bio->bi_bdev = pd->bdev;
2492 cloned_bio->bi_private = psd;
2493 cloned_bio->bi_end_io = pkt_end_io_read_cloned;
2494 pd->stats.secs_r += bio->bi_size >> 9;
2495 pkt_queue_bio(pd, cloned_bio);
2499 if (!test_bit(PACKET_WRITABLE, &pd->flags)) {
2500 printk(DRIVER_NAME": WRITE for ro device %s (%llu)\n",
2501 pd->name, (unsigned long long)bio->bi_sector);
2505 if (!bio->bi_size || (bio->bi_size % CD_FRAMESIZE)) {
2506 printk(DRIVER_NAME": wrong bio size\n");
2510 blk_queue_bounce(q, &bio);
2512 zone = ZONE(bio->bi_sector, pd);
2513 VPRINTK("pkt_make_request: start = %6llx stop = %6llx\n",
2514 (unsigned long long)bio->bi_sector,
2515 (unsigned long long)(bio->bi_sector + bio_sectors(bio)));
2517 /* Check if we have to split the bio */
2519 struct bio_pair *bp;
2523 last_zone = ZONE(bio->bi_sector + bio_sectors(bio) - 1, pd);
2524 if (last_zone != zone) {
2525 BUG_ON(last_zone != zone + pd->settings.size);
2526 first_sectors = last_zone - bio->bi_sector;
2527 bp = bio_split(bio, bio_split_pool, first_sectors);
2529 pkt_make_request(q, &bp->bio1);
2530 pkt_make_request(q, &bp->bio2);
2531 bio_pair_release(bp);
2537 * If we find a matching packet in state WAITING or READ_WAIT, we can
2538 * just append this bio to that packet.
2540 spin_lock(&pd->cdrw.active_list_lock);
2542 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
2543 if (pkt->sector == zone) {
2544 spin_lock(&pkt->lock);
2545 if ((pkt->state == PACKET_WAITING_STATE) ||
2546 (pkt->state == PACKET_READ_WAIT_STATE)) {
2547 pkt_add_list_last(bio, &pkt->orig_bios,
2548 &pkt->orig_bios_tail);
2549 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
2550 if ((pkt->write_size >= pkt->frames) &&
2551 (pkt->state == PACKET_WAITING_STATE)) {
2552 atomic_inc(&pkt->run_sm);
2553 wake_up(&pd->wqueue);
2555 spin_unlock(&pkt->lock);
2556 spin_unlock(&pd->cdrw.active_list_lock);
2561 spin_unlock(&pkt->lock);
2564 spin_unlock(&pd->cdrw.active_list_lock);
2567 * Test if there is enough room left in the bio work queue
2568 * (queue size >= congestion on mark).
2569 * If not, wait till the work queue size is below the congestion off mark.
2571 spin_lock(&pd->lock);
2572 if (pd->write_congestion_on > 0
2573 && pd->bio_queue_size >= pd->write_congestion_on) {
2574 set_bdi_congested(&q->backing_dev_info, WRITE);
2576 spin_unlock(&pd->lock);
2577 congestion_wait(WRITE, HZ);
2578 spin_lock(&pd->lock);
2579 } while(pd->bio_queue_size > pd->write_congestion_off);
2581 spin_unlock(&pd->lock);
2584 * No matching packet found. Store the bio in the work queue.
2586 node = mempool_alloc(pd->rb_pool, GFP_NOIO);
2588 spin_lock(&pd->lock);
2589 BUG_ON(pd->bio_queue_size < 0);
2590 was_empty = (pd->bio_queue_size == 0);
2591 pkt_rbtree_insert(pd, node);
2592 spin_unlock(&pd->lock);
2595 * Wake up the worker thread.
2597 atomic_set(&pd->scan_queue, 1);
2599 /* This wake_up is required for correct operation */
2600 wake_up(&pd->wqueue);
2601 } else if (!list_empty(&pd->cdrw.pkt_free_list) && !blocked_bio) {
2603 * This wake up is not required for correct operation,
2604 * but improves performance in some cases.
2606 wake_up(&pd->wqueue);
2616 static int pkt_merge_bvec(struct request_queue *q, struct bio *bio, struct bio_vec *bvec)
2618 struct pktcdvd_device *pd = q->queuedata;
2619 sector_t zone = ZONE(bio->bi_sector, pd);
2620 int used = ((bio->bi_sector - zone) << 9) + bio->bi_size;
2621 int remaining = (pd->settings.size << 9) - used;
2625 * A bio <= PAGE_SIZE must be allowed. If it crosses a packet
2626 * boundary, pkt_make_request() will split the bio.
2628 remaining2 = PAGE_SIZE - bio->bi_size;
2629 remaining = max(remaining, remaining2);
2631 BUG_ON(remaining < 0);
2635 static void pkt_init_queue(struct pktcdvd_device *pd)
2637 struct request_queue *q = pd->disk->queue;
2639 blk_queue_make_request(q, pkt_make_request);
2640 blk_queue_hardsect_size(q, CD_FRAMESIZE);
2641 blk_queue_max_sectors(q, PACKET_MAX_SECTORS);
2642 blk_queue_merge_bvec(q, pkt_merge_bvec);
2646 static int pkt_seq_show(struct seq_file *m, void *p)
2648 struct pktcdvd_device *pd = m->private;
2650 char bdev_buf[BDEVNAME_SIZE];
2651 int states[PACKET_NUM_STATES];
2653 seq_printf(m, "Writer %s mapped to %s:\n", pd->name,
2654 bdevname(pd->bdev, bdev_buf));
2656 seq_printf(m, "\nSettings:\n");
2657 seq_printf(m, "\tpacket size:\t\t%dkB\n", pd->settings.size / 2);
2659 if (pd->settings.write_type == 0)
2663 seq_printf(m, "\twrite type:\t\t%s\n", msg);
2665 seq_printf(m, "\tpacket type:\t\t%s\n", pd->settings.fp ? "Fixed" : "Variable");
2666 seq_printf(m, "\tlink loss:\t\t%d\n", pd->settings.link_loss);
2668 seq_printf(m, "\ttrack mode:\t\t%d\n", pd->settings.track_mode);
2670 if (pd->settings.block_mode == PACKET_BLOCK_MODE1)
2672 else if (pd->settings.block_mode == PACKET_BLOCK_MODE2)
2676 seq_printf(m, "\tblock mode:\t\t%s\n", msg);
2678 seq_printf(m, "\nStatistics:\n");
2679 seq_printf(m, "\tpackets started:\t%lu\n", pd->stats.pkt_started);
2680 seq_printf(m, "\tpackets ended:\t\t%lu\n", pd->stats.pkt_ended);
2681 seq_printf(m, "\twritten:\t\t%lukB\n", pd->stats.secs_w >> 1);
2682 seq_printf(m, "\tread gather:\t\t%lukB\n", pd->stats.secs_rg >> 1);
2683 seq_printf(m, "\tread:\t\t\t%lukB\n", pd->stats.secs_r >> 1);
2685 seq_printf(m, "\nMisc:\n");
2686 seq_printf(m, "\treference count:\t%d\n", pd->refcnt);
2687 seq_printf(m, "\tflags:\t\t\t0x%lx\n", pd->flags);
2688 seq_printf(m, "\tread speed:\t\t%ukB/s\n", pd->read_speed);
2689 seq_printf(m, "\twrite speed:\t\t%ukB/s\n", pd->write_speed);
2690 seq_printf(m, "\tstart offset:\t\t%lu\n", pd->offset);
2691 seq_printf(m, "\tmode page offset:\t%u\n", pd->mode_offset);
2693 seq_printf(m, "\nQueue state:\n");
2694 seq_printf(m, "\tbios queued:\t\t%d\n", pd->bio_queue_size);
2695 seq_printf(m, "\tbios pending:\t\t%d\n", atomic_read(&pd->cdrw.pending_bios));
2696 seq_printf(m, "\tcurrent sector:\t\t0x%llx\n", (unsigned long long)pd->current_sector);
2698 pkt_count_states(pd, states);
2699 seq_printf(m, "\tstate:\t\t\ti:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
2700 states[0], states[1], states[2], states[3], states[4], states[5]);
2702 seq_printf(m, "\twrite congestion marks:\toff=%d on=%d\n",
2703 pd->write_congestion_off,
2704 pd->write_congestion_on);
2708 static int pkt_seq_open(struct inode *inode, struct file *file)
2710 return single_open(file, pkt_seq_show, PDE(inode)->data);
2713 static const struct file_operations pkt_proc_fops = {
2714 .open = pkt_seq_open,
2716 .llseek = seq_lseek,
2717 .release = single_release
2720 static int pkt_new_dev(struct pktcdvd_device *pd, dev_t dev)
2724 char b[BDEVNAME_SIZE];
2725 struct proc_dir_entry *proc;
2726 struct block_device *bdev;
2728 if (pd->pkt_dev == dev) {
2729 printk(DRIVER_NAME": Recursive setup not allowed\n");
2732 for (i = 0; i < MAX_WRITERS; i++) {
2733 struct pktcdvd_device *pd2 = pkt_devs[i];
2736 if (pd2->bdev->bd_dev == dev) {
2737 printk(DRIVER_NAME": %s already setup\n", bdevname(pd2->bdev, b));
2740 if (pd2->pkt_dev == dev) {
2741 printk(DRIVER_NAME": Can't chain pktcdvd devices\n");
2749 ret = blkdev_get(bdev, FMODE_READ, O_RDONLY | O_NONBLOCK);
2753 /* This is safe, since we have a reference from open(). */
2754 __module_get(THIS_MODULE);
2757 set_blocksize(bdev, CD_FRAMESIZE);
2761 atomic_set(&pd->cdrw.pending_bios, 0);
2762 pd->cdrw.thread = kthread_run(kcdrwd, pd, "%s", pd->name);
2763 if (IS_ERR(pd->cdrw.thread)) {
2764 printk(DRIVER_NAME": can't start kernel thread\n");
2769 proc = create_proc_entry(pd->name, 0, pkt_proc);
2772 proc->proc_fops = &pkt_proc_fops;
2774 DPRINTK(DRIVER_NAME": writer %s mapped to %s\n", pd->name, bdevname(bdev, b));
2779 /* This is safe: open() is still holding a reference. */
2780 module_put(THIS_MODULE);
2784 static int pkt_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2786 struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2788 VPRINTK("pkt_ioctl: cmd %x, dev %d:%d\n", cmd, imajor(inode), iminor(inode));
2792 * forward selected CDROM ioctls to CD-ROM, for UDF
2794 case CDROMMULTISESSION:
2795 case CDROMREADTOCENTRY:
2796 case CDROM_LAST_WRITTEN:
2797 case CDROM_SEND_PACKET:
2798 case SCSI_IOCTL_SEND_COMMAND:
2799 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2803 * The door gets locked when the device is opened, so we
2804 * have to unlock it or else the eject command fails.
2806 if (pd->refcnt == 1)
2807 pkt_lock_door(pd, 0);
2808 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2811 VPRINTK(DRIVER_NAME": Unknown ioctl for %s (%x)\n", pd->name, cmd);
2818 static int pkt_media_changed(struct gendisk *disk)
2820 struct pktcdvd_device *pd = disk->private_data;
2821 struct gendisk *attached_disk;
2827 attached_disk = pd->bdev->bd_disk;
2830 return attached_disk->fops->media_changed(attached_disk);
2833 static struct block_device_operations pktcdvd_ops = {
2834 .owner = THIS_MODULE,
2836 .release = pkt_close,
2838 .media_changed = pkt_media_changed,
2842 * Set up mapping from pktcdvd device to CD-ROM device.
2844 static int pkt_setup_dev(dev_t dev, dev_t* pkt_dev)
2848 struct pktcdvd_device *pd;
2849 struct gendisk *disk;
2851 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
2853 for (idx = 0; idx < MAX_WRITERS; idx++)
2856 if (idx == MAX_WRITERS) {
2857 printk(DRIVER_NAME": max %d writers supported\n", MAX_WRITERS);
2862 pd = kzalloc(sizeof(struct pktcdvd_device), GFP_KERNEL);
2866 pd->rb_pool = mempool_create_kmalloc_pool(PKT_RB_POOL_SIZE,
2867 sizeof(struct pkt_rb_node));
2871 INIT_LIST_HEAD(&pd->cdrw.pkt_free_list);
2872 INIT_LIST_HEAD(&pd->cdrw.pkt_active_list);
2873 spin_lock_init(&pd->cdrw.active_list_lock);
2875 spin_lock_init(&pd->lock);
2876 spin_lock_init(&pd->iosched.lock);
2877 sprintf(pd->name, DRIVER_NAME"%d", idx);
2878 init_waitqueue_head(&pd->wqueue);
2879 pd->bio_queue = RB_ROOT;
2881 pd->write_congestion_on = write_congestion_on;
2882 pd->write_congestion_off = write_congestion_off;
2884 disk = alloc_disk(1);
2888 disk->major = pktdev_major;
2889 disk->first_minor = idx;
2890 disk->fops = &pktcdvd_ops;
2891 disk->flags = GENHD_FL_REMOVABLE;
2892 strcpy(disk->disk_name, pd->name);
2893 disk->private_data = pd;
2894 disk->queue = blk_alloc_queue(GFP_KERNEL);
2898 pd->pkt_dev = MKDEV(disk->major, disk->first_minor);
2899 ret = pkt_new_dev(pd, dev);
2905 pkt_sysfs_dev_new(pd);
2906 pkt_debugfs_dev_new(pd);
2910 *pkt_dev = pd->pkt_dev;
2912 mutex_unlock(&ctl_mutex);
2916 blk_cleanup_queue(disk->queue);
2921 mempool_destroy(pd->rb_pool);
2924 mutex_unlock(&ctl_mutex);
2925 printk(DRIVER_NAME": setup of pktcdvd device failed\n");
2930 * Tear down mapping from pktcdvd device to CD-ROM device.
2932 static int pkt_remove_dev(dev_t pkt_dev)
2934 struct pktcdvd_device *pd;
2938 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
2940 for (idx = 0; idx < MAX_WRITERS; idx++) {
2942 if (pd && (pd->pkt_dev == pkt_dev))
2945 if (idx == MAX_WRITERS) {
2946 DPRINTK(DRIVER_NAME": dev not setup\n");
2951 if (pd->refcnt > 0) {
2955 if (!IS_ERR(pd->cdrw.thread))
2956 kthread_stop(pd->cdrw.thread);
2958 pkt_devs[idx] = NULL;
2960 pkt_debugfs_dev_remove(pd);
2961 pkt_sysfs_dev_remove(pd);
2963 blkdev_put(pd->bdev);
2965 remove_proc_entry(pd->name, pkt_proc);
2966 DPRINTK(DRIVER_NAME": writer %s unmapped\n", pd->name);
2968 del_gendisk(pd->disk);
2969 blk_cleanup_queue(pd->disk->queue);
2972 mempool_destroy(pd->rb_pool);
2975 /* This is safe: open() is still holding a reference. */
2976 module_put(THIS_MODULE);
2979 mutex_unlock(&ctl_mutex);
2983 static void pkt_get_status(struct pkt_ctrl_command *ctrl_cmd)
2985 struct pktcdvd_device *pd;
2987 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
2989 pd = pkt_find_dev_from_minor(ctrl_cmd->dev_index);
2991 ctrl_cmd->dev = new_encode_dev(pd->bdev->bd_dev);
2992 ctrl_cmd->pkt_dev = new_encode_dev(pd->pkt_dev);
2995 ctrl_cmd->pkt_dev = 0;
2997 ctrl_cmd->num_devices = MAX_WRITERS;
2999 mutex_unlock(&ctl_mutex);
3002 static int pkt_ctl_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
3004 void __user *argp = (void __user *)arg;
3005 struct pkt_ctrl_command ctrl_cmd;
3009 if (cmd != PACKET_CTRL_CMD)
3012 if (copy_from_user(&ctrl_cmd, argp, sizeof(struct pkt_ctrl_command)))
3015 switch (ctrl_cmd.command) {
3016 case PKT_CTRL_CMD_SETUP:
3017 if (!capable(CAP_SYS_ADMIN))
3019 ret = pkt_setup_dev(new_decode_dev(ctrl_cmd.dev), &pkt_dev);
3020 ctrl_cmd.pkt_dev = new_encode_dev(pkt_dev);
3022 case PKT_CTRL_CMD_TEARDOWN:
3023 if (!capable(CAP_SYS_ADMIN))
3025 ret = pkt_remove_dev(new_decode_dev(ctrl_cmd.pkt_dev));
3027 case PKT_CTRL_CMD_STATUS:
3028 pkt_get_status(&ctrl_cmd);
3034 if (copy_to_user(argp, &ctrl_cmd, sizeof(struct pkt_ctrl_command)))
3040 static const struct file_operations pkt_ctl_fops = {
3041 .ioctl = pkt_ctl_ioctl,
3042 .owner = THIS_MODULE,
3045 static struct miscdevice pkt_misc = {
3046 .minor = MISC_DYNAMIC_MINOR,
3047 .name = DRIVER_NAME,
3048 .fops = &pkt_ctl_fops
3051 static int __init pkt_init(void)
3055 mutex_init(&ctl_mutex);
3057 psd_pool = mempool_create_kmalloc_pool(PSD_POOL_SIZE,
3058 sizeof(struct packet_stacked_data));
3062 ret = register_blkdev(pktdev_major, DRIVER_NAME);
3064 printk(DRIVER_NAME": Unable to register block device\n");
3070 ret = pkt_sysfs_init();
3076 ret = misc_register(&pkt_misc);
3078 printk(DRIVER_NAME": Unable to register misc device\n");
3082 pkt_proc = proc_mkdir(DRIVER_NAME, proc_root_driver);
3087 pkt_debugfs_cleanup();
3088 pkt_sysfs_cleanup();
3090 unregister_blkdev(pktdev_major, DRIVER_NAME);
3092 mempool_destroy(psd_pool);
3096 static void __exit pkt_exit(void)
3098 remove_proc_entry(DRIVER_NAME, proc_root_driver);
3099 misc_deregister(&pkt_misc);
3101 pkt_debugfs_cleanup();
3102 pkt_sysfs_cleanup();
3104 unregister_blkdev(pktdev_major, DRIVER_NAME);
3105 mempool_destroy(psd_pool);
3108 MODULE_DESCRIPTION("Packet writing layer for CD/DVD drives");
3109 MODULE_AUTHOR("Jens Axboe <axboe@suse.de>");
3110 MODULE_LICENSE("GPL");
3112 module_init(pkt_init);
3113 module_exit(pkt_exit);