revert-mm-fix-blkdev-size-calculation-in-generic_write_checks
[linux-2.6/linux-trees-mm.git] / drivers / block / pktcdvd.c
blob399649e9bccb78aa22bde78866ba066cb493cc2c
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>
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
10 * DVD-RAM devices.
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"
70 #if PACKET_DEBUG
71 #define DPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
72 #else
73 #define DPRINTK(fmt, args...)
74 #endif
76 #if PACKET_DEBUG > 1
77 #define VPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
78 #else
79 #define VPRINTK(fmt, args...)
80 #endif
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,
108 const char* name,
109 struct kobject* parent,
110 struct kobj_type* ktype)
112 struct pktcdvd_kobj *p;
113 p = kzalloc(sizeof(*p), GFP_KERNEL);
114 if (!p)
115 return NULL;
116 kobject_set_name(&p->kobj, "%s", name);
117 p->kobj.parent = parent;
118 p->kobj.ktype = ktype;
119 p->pd = pd;
120 if (kobject_register(&p->kobj) != 0)
121 return NULL;
122 return p;
125 * remove a pktcdvd kernel object.
127 static void pkt_kobj_remove(struct pktcdvd_kobj *p)
129 if (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]/
153 stat/reset
154 stat/packets_started
155 stat/packets_finished
156 stat/kb_written
157 stat/kb_read
158 stat/kb_read_gather
159 write_queue/size
160 write_queue/congestion_off
161 write_queue/congestion_on
162 **********************************************************/
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[] = {
172 &kobj_pkt_attr_st1,
173 &kobj_pkt_attr_st2,
174 &kobj_pkt_attr_st3,
175 &kobj_pkt_attr_st4,
176 &kobj_pkt_attr_st5,
177 &kobj_pkt_attr_st6,
178 NULL
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[] = {
186 &kobj_pkt_attr_wq1,
187 &kobj_pkt_attr_wq2,
188 &kobj_pkt_attr_wq3,
189 NULL
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;
196 int n = 0;
197 int v;
198 if (strcmp(attr->name, "packets_started") == 0) {
199 n = sprintf(data, "%lu\n", pd->stats.pkt_started);
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);
231 return n;
234 static void init_write_congestion_marks(int* lo, int* hi)
236 if (*hi > 0) {
237 *hi = max(*hi, 500);
238 *hi = min(*hi, 1000000);
239 if (*lo <= 0)
240 *lo = *hi - 100;
241 else {
242 *lo = min(*lo, *hi - 100);
243 *lo = max(*lo, 100);
245 } else {
246 *hi = -1;
247 *lo = -1;
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;
256 int val;
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);
281 return len;
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)
301 if (class_pktcdvd) {
302 pd->dev = device_create(class_pktcdvd, NULL, pd->pkt_dev, "%s", pd->name);
303 if (IS_ERR(pd->dev))
304 pd->dev = NULL;
306 if (pd->dev) {
307 pd->kobj_stat = pkt_kobj_create(pd, "stat",
308 &pd->dev->kobj,
309 &kobj_pkt_type_stat);
310 pd->kobj_wqueue = pkt_kobj_create(pd, "write_queue",
311 &pd->dev->kobj,
312 &kobj_pkt_type_wqueue);
316 static void pkt_sysfs_dev_remove(struct pktcdvd_device *pd)
318 pkt_kobj_remove(pd->kobj_stat);
319 pkt_kobj_remove(pd->kobj_wqueue);
320 if (class_pktcdvd)
321 device_destroy(class_pktcdvd, pd->pkt_dev);
325 /********************************************************************
326 /sys/class/pktcdvd/
327 add map block device
328 remove unmap packet dev
329 device_map show mappings
330 *******************************************************************/
332 static void class_pktcdvd_release(struct class *cls)
334 kfree(cls);
336 static ssize_t class_pktcdvd_show_map(struct class *c, char *data)
338 int n = 0;
339 int idx;
340 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
341 for (idx = 0; idx < MAX_WRITERS; idx++) {
342 struct pktcdvd_device *pd = pkt_devs[idx];
343 if (!pd)
344 continue;
345 n += sprintf(data+n, "%s %u:%u %u:%u\n",
346 pd->name,
347 MAJOR(pd->pkt_dev), MINOR(pd->pkt_dev),
348 MAJOR(pd->bdev->bd_dev),
349 MINOR(pd->bdev->bd_dev));
351 mutex_unlock(&ctl_mutex);
352 return n;
355 static ssize_t class_pktcdvd_store_add(struct class *c, const char *buf,
356 size_t count)
358 unsigned int major, minor;
360 if (sscanf(buf, "%u:%u", &major, &minor) == 2) {
361 /* pkt_setup_dev() expects caller to hold reference to self */
362 if (!try_module_get(THIS_MODULE))
363 return -ENODEV;
365 pkt_setup_dev(MKDEV(major, minor), NULL);
367 module_put(THIS_MODULE);
369 return count;
372 return -EINVAL;
375 static ssize_t class_pktcdvd_store_remove(struct class *c, const char *buf,
376 size_t count)
378 unsigned int major, minor;
379 if (sscanf(buf, "%u:%u", &major, &minor) == 2) {
380 pkt_remove_dev(MKDEV(major, minor));
381 return count;
383 return -EINVAL;
386 static struct class_attribute class_pktcdvd_attrs[] = {
387 __ATTR(add, 0200, NULL, class_pktcdvd_store_add),
388 __ATTR(remove, 0200, NULL, class_pktcdvd_store_remove),
389 __ATTR(device_map, 0444, class_pktcdvd_show_map, NULL),
390 __ATTR_NULL
394 static int pkt_sysfs_init(void)
396 int ret = 0;
399 * create control files in sysfs
400 * /sys/class/pktcdvd/...
402 class_pktcdvd = kzalloc(sizeof(*class_pktcdvd), GFP_KERNEL);
403 if (!class_pktcdvd)
404 return -ENOMEM;
405 class_pktcdvd->name = DRIVER_NAME;
406 class_pktcdvd->owner = THIS_MODULE;
407 class_pktcdvd->class_release = class_pktcdvd_release;
408 class_pktcdvd->class_attrs = class_pktcdvd_attrs;
409 ret = class_register(class_pktcdvd);
410 if (ret) {
411 kfree(class_pktcdvd);
412 class_pktcdvd = NULL;
413 printk(DRIVER_NAME": failed to create class pktcdvd\n");
414 return ret;
416 return 0;
419 static void pkt_sysfs_cleanup(void)
421 if (class_pktcdvd)
422 class_destroy(class_pktcdvd);
423 class_pktcdvd = NULL;
426 /********************************************************************
427 entries in debugfs
429 /debugfs/pktcdvd[0-7]/
430 info
432 *******************************************************************/
434 static int pkt_debugfs_seq_show(struct seq_file *m, void *p)
436 return pkt_seq_show(m, p);
439 static int pkt_debugfs_fops_open(struct inode *inode, struct file *file)
441 return single_open(file, pkt_debugfs_seq_show, inode->i_private);
444 static const struct file_operations debug_fops = {
445 .open = pkt_debugfs_fops_open,
446 .read = seq_read,
447 .llseek = seq_lseek,
448 .release = single_release,
449 .owner = THIS_MODULE,
452 static void pkt_debugfs_dev_new(struct pktcdvd_device *pd)
454 if (!pkt_debugfs_root)
455 return;
456 pd->dfs_f_info = NULL;
457 pd->dfs_d_root = debugfs_create_dir(pd->name, pkt_debugfs_root);
458 if (IS_ERR(pd->dfs_d_root)) {
459 pd->dfs_d_root = NULL;
460 return;
462 pd->dfs_f_info = debugfs_create_file("info", S_IRUGO,
463 pd->dfs_d_root, pd, &debug_fops);
464 if (IS_ERR(pd->dfs_f_info)) {
465 pd->dfs_f_info = NULL;
466 return;
470 static void pkt_debugfs_dev_remove(struct pktcdvd_device *pd)
472 if (!pkt_debugfs_root)
473 return;
474 if (pd->dfs_f_info)
475 debugfs_remove(pd->dfs_f_info);
476 pd->dfs_f_info = NULL;
477 if (pd->dfs_d_root)
478 debugfs_remove(pd->dfs_d_root);
479 pd->dfs_d_root = NULL;
482 static void pkt_debugfs_init(void)
484 pkt_debugfs_root = debugfs_create_dir(DRIVER_NAME, NULL);
485 if (IS_ERR(pkt_debugfs_root)) {
486 pkt_debugfs_root = NULL;
487 return;
491 static void pkt_debugfs_cleanup(void)
493 if (!pkt_debugfs_root)
494 return;
495 debugfs_remove(pkt_debugfs_root);
496 pkt_debugfs_root = NULL;
499 /* ----------------------------------------------------------*/
502 static void pkt_bio_finished(struct pktcdvd_device *pd)
504 BUG_ON(atomic_read(&pd->cdrw.pending_bios) <= 0);
505 if (atomic_dec_and_test(&pd->cdrw.pending_bios)) {
506 VPRINTK(DRIVER_NAME": queue empty\n");
507 atomic_set(&pd->iosched.attention, 1);
508 wake_up(&pd->wqueue);
512 static void pkt_bio_destructor(struct bio *bio)
514 kfree(bio->bi_io_vec);
515 kfree(bio);
518 static struct bio *pkt_bio_alloc(int nr_iovecs)
520 struct bio_vec *bvl = NULL;
521 struct bio *bio;
523 bio = kmalloc(sizeof(struct bio), GFP_KERNEL);
524 if (!bio)
525 goto no_bio;
526 bio_init(bio);
528 bvl = kcalloc(nr_iovecs, sizeof(struct bio_vec), GFP_KERNEL);
529 if (!bvl)
530 goto no_bvl;
532 bio->bi_max_vecs = nr_iovecs;
533 bio->bi_io_vec = bvl;
534 bio->bi_destructor = pkt_bio_destructor;
536 return bio;
538 no_bvl:
539 kfree(bio);
540 no_bio:
541 return NULL;
545 * Allocate a packet_data struct
547 static struct packet_data *pkt_alloc_packet_data(int frames)
549 int i;
550 struct packet_data *pkt;
552 pkt = kzalloc(sizeof(struct packet_data), GFP_KERNEL);
553 if (!pkt)
554 goto no_pkt;
556 pkt->frames = frames;
557 pkt->w_bio = pkt_bio_alloc(frames);
558 if (!pkt->w_bio)
559 goto no_bio;
561 for (i = 0; i < frames / FRAMES_PER_PAGE; i++) {
562 pkt->pages[i] = alloc_page(GFP_KERNEL|__GFP_ZERO);
563 if (!pkt->pages[i])
564 goto no_page;
567 spin_lock_init(&pkt->lock);
569 for (i = 0; i < frames; i++) {
570 struct bio *bio = pkt_bio_alloc(1);
571 if (!bio)
572 goto no_rd_bio;
573 pkt->r_bios[i] = bio;
576 return pkt;
578 no_rd_bio:
579 for (i = 0; i < frames; i++) {
580 struct bio *bio = pkt->r_bios[i];
581 if (bio)
582 bio_put(bio);
585 no_page:
586 for (i = 0; i < frames / FRAMES_PER_PAGE; i++)
587 if (pkt->pages[i])
588 __free_page(pkt->pages[i]);
589 bio_put(pkt->w_bio);
590 no_bio:
591 kfree(pkt);
592 no_pkt:
593 return NULL;
597 * Free a packet_data struct
599 static void pkt_free_packet_data(struct packet_data *pkt)
601 int i;
603 for (i = 0; i < pkt->frames; i++) {
604 struct bio *bio = pkt->r_bios[i];
605 if (bio)
606 bio_put(bio);
608 for (i = 0; i < pkt->frames / FRAMES_PER_PAGE; i++)
609 __free_page(pkt->pages[i]);
610 bio_put(pkt->w_bio);
611 kfree(pkt);
614 static void pkt_shrink_pktlist(struct pktcdvd_device *pd)
616 struct packet_data *pkt, *next;
618 BUG_ON(!list_empty(&pd->cdrw.pkt_active_list));
620 list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_free_list, list) {
621 pkt_free_packet_data(pkt);
623 INIT_LIST_HEAD(&pd->cdrw.pkt_free_list);
626 static int pkt_grow_pktlist(struct pktcdvd_device *pd, int nr_packets)
628 struct packet_data *pkt;
630 BUG_ON(!list_empty(&pd->cdrw.pkt_free_list));
632 while (nr_packets > 0) {
633 pkt = pkt_alloc_packet_data(pd->settings.size >> 2);
634 if (!pkt) {
635 pkt_shrink_pktlist(pd);
636 return 0;
638 pkt->id = nr_packets;
639 pkt->pd = pd;
640 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
641 nr_packets--;
643 return 1;
646 static inline struct pkt_rb_node *pkt_rbtree_next(struct pkt_rb_node *node)
648 struct rb_node *n = rb_next(&node->rb_node);
649 if (!n)
650 return NULL;
651 return rb_entry(n, struct pkt_rb_node, rb_node);
654 static void pkt_rbtree_erase(struct pktcdvd_device *pd, struct pkt_rb_node *node)
656 rb_erase(&node->rb_node, &pd->bio_queue);
657 mempool_free(node, pd->rb_pool);
658 pd->bio_queue_size--;
659 BUG_ON(pd->bio_queue_size < 0);
663 * Find the first node in the pd->bio_queue rb tree with a starting sector >= s.
665 static struct pkt_rb_node *pkt_rbtree_find(struct pktcdvd_device *pd, sector_t s)
667 struct rb_node *n = pd->bio_queue.rb_node;
668 struct rb_node *next;
669 struct pkt_rb_node *tmp;
671 if (!n) {
672 BUG_ON(pd->bio_queue_size > 0);
673 return NULL;
676 for (;;) {
677 tmp = rb_entry(n, struct pkt_rb_node, rb_node);
678 if (s <= tmp->bio->bi_sector)
679 next = n->rb_left;
680 else
681 next = n->rb_right;
682 if (!next)
683 break;
684 n = next;
687 if (s > tmp->bio->bi_sector) {
688 tmp = pkt_rbtree_next(tmp);
689 if (!tmp)
690 return NULL;
692 BUG_ON(s > tmp->bio->bi_sector);
693 return tmp;
697 * Insert a node into the pd->bio_queue rb tree.
699 static void pkt_rbtree_insert(struct pktcdvd_device *pd, struct pkt_rb_node *node)
701 struct rb_node **p = &pd->bio_queue.rb_node;
702 struct rb_node *parent = NULL;
703 sector_t s = node->bio->bi_sector;
704 struct pkt_rb_node *tmp;
706 while (*p) {
707 parent = *p;
708 tmp = rb_entry(parent, struct pkt_rb_node, rb_node);
709 if (s < tmp->bio->bi_sector)
710 p = &(*p)->rb_left;
711 else
712 p = &(*p)->rb_right;
714 rb_link_node(&node->rb_node, parent, p);
715 rb_insert_color(&node->rb_node, &pd->bio_queue);
716 pd->bio_queue_size++;
720 * Add a bio to a single linked list defined by its head and tail pointers.
722 static void pkt_add_list_last(struct bio *bio, struct bio **list_head, struct bio **list_tail)
724 bio->bi_next = NULL;
725 if (*list_tail) {
726 BUG_ON((*list_head) == NULL);
727 (*list_tail)->bi_next = bio;
728 (*list_tail) = bio;
729 } else {
730 BUG_ON((*list_head) != NULL);
731 (*list_head) = bio;
732 (*list_tail) = bio;
737 * Remove and return the first bio from a single linked list defined by its
738 * head and tail pointers.
740 static inline struct bio *pkt_get_list_first(struct bio **list_head, struct bio **list_tail)
742 struct bio *bio;
744 if (*list_head == NULL)
745 return NULL;
747 bio = *list_head;
748 *list_head = bio->bi_next;
749 if (*list_head == NULL)
750 *list_tail = NULL;
752 bio->bi_next = NULL;
753 return bio;
757 * Send a packet_command to the underlying block device and
758 * wait for completion.
760 static int pkt_generic_packet(struct pktcdvd_device *pd, struct packet_command *cgc)
762 struct request_queue *q = bdev_get_queue(pd->bdev);
763 struct request *rq;
764 int ret = 0;
766 rq = blk_get_request(q, (cgc->data_direction == CGC_DATA_WRITE) ?
767 WRITE : READ, __GFP_WAIT);
769 if (cgc->buflen) {
770 if (blk_rq_map_kern(q, rq, cgc->buffer, cgc->buflen, __GFP_WAIT))
771 goto out;
774 rq->cmd_len = COMMAND_SIZE(cgc->cmd[0]);
775 memcpy(rq->cmd, cgc->cmd, CDROM_PACKET_SIZE);
776 if (sizeof(rq->cmd) > CDROM_PACKET_SIZE)
777 memset(rq->cmd + CDROM_PACKET_SIZE, 0, sizeof(rq->cmd) - CDROM_PACKET_SIZE);
779 rq->timeout = 60*HZ;
780 rq->cmd_type = REQ_TYPE_BLOCK_PC;
781 rq->cmd_flags |= REQ_HARDBARRIER;
782 if (cgc->quiet)
783 rq->cmd_flags |= REQ_QUIET;
785 blk_execute_rq(rq->q, pd->bdev->bd_disk, rq, 0);
786 if (rq->errors)
787 ret = -EIO;
788 out:
789 blk_put_request(rq);
790 return ret;
794 * A generic sense dump / resolve mechanism should be implemented across
795 * all ATAPI + SCSI devices.
797 static void pkt_dump_sense(struct packet_command *cgc)
799 static char *info[9] = { "No sense", "Recovered error", "Not ready",
800 "Medium error", "Hardware error", "Illegal request",
801 "Unit attention", "Data protect", "Blank check" };
802 int i;
803 struct request_sense *sense = cgc->sense;
805 printk(DRIVER_NAME":");
806 for (i = 0; i < CDROM_PACKET_SIZE; i++)
807 printk(" %02x", cgc->cmd[i]);
808 printk(" - ");
810 if (sense == NULL) {
811 printk("no sense\n");
812 return;
815 printk("sense %02x.%02x.%02x", sense->sense_key, sense->asc, sense->ascq);
817 if (sense->sense_key > 8) {
818 printk(" (INVALID)\n");
819 return;
822 printk(" (%s)\n", info[sense->sense_key]);
826 * flush the drive cache to media
828 static int pkt_flush_cache(struct pktcdvd_device *pd)
830 struct packet_command cgc;
832 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
833 cgc.cmd[0] = GPCMD_FLUSH_CACHE;
834 cgc.quiet = 1;
837 * the IMMED bit -- we default to not setting it, although that
838 * would allow a much faster close, this is safer
840 #if 0
841 cgc.cmd[1] = 1 << 1;
842 #endif
843 return pkt_generic_packet(pd, &cgc);
847 * speed is given as the normal factor, e.g. 4 for 4x
849 static int pkt_set_speed(struct pktcdvd_device *pd, unsigned write_speed, unsigned read_speed)
851 struct packet_command cgc;
852 struct request_sense sense;
853 int ret;
855 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
856 cgc.sense = &sense;
857 cgc.cmd[0] = GPCMD_SET_SPEED;
858 cgc.cmd[2] = (read_speed >> 8) & 0xff;
859 cgc.cmd[3] = read_speed & 0xff;
860 cgc.cmd[4] = (write_speed >> 8) & 0xff;
861 cgc.cmd[5] = write_speed & 0xff;
863 if ((ret = pkt_generic_packet(pd, &cgc)))
864 pkt_dump_sense(&cgc);
866 return ret;
870 * Queue a bio for processing by the low-level CD device. Must be called
871 * from process context.
873 static void pkt_queue_bio(struct pktcdvd_device *pd, struct bio *bio)
875 spin_lock(&pd->iosched.lock);
876 if (bio_data_dir(bio) == READ) {
877 pkt_add_list_last(bio, &pd->iosched.read_queue,
878 &pd->iosched.read_queue_tail);
879 } else {
880 pkt_add_list_last(bio, &pd->iosched.write_queue,
881 &pd->iosched.write_queue_tail);
883 spin_unlock(&pd->iosched.lock);
885 atomic_set(&pd->iosched.attention, 1);
886 wake_up(&pd->wqueue);
890 * Process the queued read/write requests. This function handles special
891 * requirements for CDRW drives:
892 * - A cache flush command must be inserted before a read request if the
893 * previous request was a write.
894 * - Switching between reading and writing is slow, so don't do it more often
895 * than necessary.
896 * - Optimize for throughput at the expense of latency. This means that streaming
897 * writes will never be interrupted by a read, but if the drive has to seek
898 * before the next write, switch to reading instead if there are any pending
899 * read requests.
900 * - Set the read speed according to current usage pattern. When only reading
901 * from the device, it's best to use the highest possible read speed, but
902 * when switching often between reading and writing, it's better to have the
903 * same read and write speeds.
905 static void pkt_iosched_process_queue(struct pktcdvd_device *pd)
908 if (atomic_read(&pd->iosched.attention) == 0)
909 return;
910 atomic_set(&pd->iosched.attention, 0);
912 for (;;) {
913 struct bio *bio;
914 int reads_queued, writes_queued;
916 spin_lock(&pd->iosched.lock);
917 reads_queued = (pd->iosched.read_queue != NULL);
918 writes_queued = (pd->iosched.write_queue != NULL);
919 spin_unlock(&pd->iosched.lock);
921 if (!reads_queued && !writes_queued)
922 break;
924 if (pd->iosched.writing) {
925 int need_write_seek = 1;
926 spin_lock(&pd->iosched.lock);
927 bio = pd->iosched.write_queue;
928 spin_unlock(&pd->iosched.lock);
929 if (bio && (bio->bi_sector == pd->iosched.last_write))
930 need_write_seek = 0;
931 if (need_write_seek && reads_queued) {
932 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
933 VPRINTK(DRIVER_NAME": write, waiting\n");
934 break;
936 pkt_flush_cache(pd);
937 pd->iosched.writing = 0;
939 } else {
940 if (!reads_queued && writes_queued) {
941 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
942 VPRINTK(DRIVER_NAME": read, waiting\n");
943 break;
945 pd->iosched.writing = 1;
949 spin_lock(&pd->iosched.lock);
950 if (pd->iosched.writing) {
951 bio = pkt_get_list_first(&pd->iosched.write_queue,
952 &pd->iosched.write_queue_tail);
953 } else {
954 bio = pkt_get_list_first(&pd->iosched.read_queue,
955 &pd->iosched.read_queue_tail);
957 spin_unlock(&pd->iosched.lock);
959 if (!bio)
960 continue;
962 if (bio_data_dir(bio) == READ)
963 pd->iosched.successive_reads += bio->bi_size >> 10;
964 else {
965 pd->iosched.successive_reads = 0;
966 pd->iosched.last_write = bio->bi_sector + bio_sectors(bio);
968 if (pd->iosched.successive_reads >= HI_SPEED_SWITCH) {
969 if (pd->read_speed == pd->write_speed) {
970 pd->read_speed = MAX_SPEED;
971 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
973 } else {
974 if (pd->read_speed != pd->write_speed) {
975 pd->read_speed = pd->write_speed;
976 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
980 atomic_inc(&pd->cdrw.pending_bios);
981 generic_make_request(bio);
986 * Special care is needed if the underlying block device has a small
987 * max_phys_segments value.
989 static int pkt_set_segment_merging(struct pktcdvd_device *pd, struct request_queue *q)
991 if ((pd->settings.size << 9) / CD_FRAMESIZE <= q->max_phys_segments) {
993 * The cdrom device can handle one segment/frame
995 clear_bit(PACKET_MERGE_SEGS, &pd->flags);
996 return 0;
997 } else if ((pd->settings.size << 9) / PAGE_SIZE <= q->max_phys_segments) {
999 * We can handle this case at the expense of some extra memory
1000 * copies during write operations
1002 set_bit(PACKET_MERGE_SEGS, &pd->flags);
1003 return 0;
1004 } else {
1005 printk(DRIVER_NAME": cdrom max_phys_segments too small\n");
1006 return -EIO;
1011 * Copy CD_FRAMESIZE bytes from src_bio into a destination page
1013 static void pkt_copy_bio_data(struct bio *src_bio, int seg, int offs, struct page *dst_page, int dst_offs)
1015 unsigned int copy_size = CD_FRAMESIZE;
1017 while (copy_size > 0) {
1018 struct bio_vec *src_bvl = bio_iovec_idx(src_bio, seg);
1019 void *vfrom = kmap_atomic(src_bvl->bv_page, KM_USER0) +
1020 src_bvl->bv_offset + offs;
1021 void *vto = page_address(dst_page) + dst_offs;
1022 int len = min_t(int, copy_size, src_bvl->bv_len - offs);
1024 BUG_ON(len < 0);
1025 memcpy(vto, vfrom, len);
1026 kunmap_atomic(vfrom, KM_USER0);
1028 seg++;
1029 offs = 0;
1030 dst_offs += len;
1031 copy_size -= len;
1036 * Copy all data for this packet to pkt->pages[], so that
1037 * a) The number of required segments for the write bio is minimized, which
1038 * is necessary for some scsi controllers.
1039 * b) The data can be used as cache to avoid read requests if we receive a
1040 * new write request for the same zone.
1042 static void pkt_make_local_copy(struct packet_data *pkt, struct bio_vec *bvec)
1044 int f, p, offs;
1046 /* Copy all data to pkt->pages[] */
1047 p = 0;
1048 offs = 0;
1049 for (f = 0; f < pkt->frames; f++) {
1050 if (bvec[f].bv_page != pkt->pages[p]) {
1051 void *vfrom = kmap_atomic(bvec[f].bv_page, KM_USER0) + bvec[f].bv_offset;
1052 void *vto = page_address(pkt->pages[p]) + offs;
1053 memcpy(vto, vfrom, CD_FRAMESIZE);
1054 kunmap_atomic(vfrom, KM_USER0);
1055 bvec[f].bv_page = pkt->pages[p];
1056 bvec[f].bv_offset = offs;
1057 } else {
1058 BUG_ON(bvec[f].bv_offset != offs);
1060 offs += CD_FRAMESIZE;
1061 if (offs >= PAGE_SIZE) {
1062 offs = 0;
1063 p++;
1068 static void pkt_end_io_read(struct bio *bio, int err)
1070 struct packet_data *pkt = bio->bi_private;
1071 struct pktcdvd_device *pd = pkt->pd;
1072 BUG_ON(!pd);
1074 VPRINTK("pkt_end_io_read: bio=%p sec0=%llx sec=%llx err=%d\n", bio,
1075 (unsigned long long)pkt->sector, (unsigned long long)bio->bi_sector, err);
1077 if (err)
1078 atomic_inc(&pkt->io_errors);
1079 if (atomic_dec_and_test(&pkt->io_wait)) {
1080 atomic_inc(&pkt->run_sm);
1081 wake_up(&pd->wqueue);
1083 pkt_bio_finished(pd);
1086 static void pkt_end_io_packet_write(struct bio *bio, int err)
1088 struct packet_data *pkt = bio->bi_private;
1089 struct pktcdvd_device *pd = pkt->pd;
1090 BUG_ON(!pd);
1092 VPRINTK("pkt_end_io_packet_write: id=%d, err=%d\n", pkt->id, err);
1094 pd->stats.pkt_ended++;
1096 pkt_bio_finished(pd);
1097 atomic_dec(&pkt->io_wait);
1098 atomic_inc(&pkt->run_sm);
1099 wake_up(&pd->wqueue);
1103 * Schedule reads for the holes in a packet
1105 static void pkt_gather_data(struct pktcdvd_device *pd, struct packet_data *pkt)
1107 int frames_read = 0;
1108 struct bio *bio;
1109 int f;
1110 char written[PACKET_MAX_SIZE];
1112 BUG_ON(!pkt->orig_bios);
1114 atomic_set(&pkt->io_wait, 0);
1115 atomic_set(&pkt->io_errors, 0);
1118 * Figure out which frames we need to read before we can write.
1120 memset(written, 0, sizeof(written));
1121 spin_lock(&pkt->lock);
1122 for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
1123 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
1124 int num_frames = bio->bi_size / CD_FRAMESIZE;
1125 pd->stats.secs_w += num_frames * (CD_FRAMESIZE >> 9);
1126 BUG_ON(first_frame < 0);
1127 BUG_ON(first_frame + num_frames > pkt->frames);
1128 for (f = first_frame; f < first_frame + num_frames; f++)
1129 written[f] = 1;
1131 spin_unlock(&pkt->lock);
1133 if (pkt->cache_valid) {
1134 VPRINTK("pkt_gather_data: zone %llx cached\n",
1135 (unsigned long long)pkt->sector);
1136 goto out_account;
1140 * Schedule reads for missing parts of the packet.
1142 for (f = 0; f < pkt->frames; f++) {
1143 struct bio_vec *vec;
1145 int p, offset;
1146 if (written[f])
1147 continue;
1148 bio = pkt->r_bios[f];
1149 vec = bio->bi_io_vec;
1150 bio_init(bio);
1151 bio->bi_max_vecs = 1;
1152 bio->bi_sector = pkt->sector + f * (CD_FRAMESIZE >> 9);
1153 bio->bi_bdev = pd->bdev;
1154 bio->bi_end_io = pkt_end_io_read;
1155 bio->bi_private = pkt;
1156 bio->bi_io_vec = vec;
1157 bio->bi_destructor = pkt_bio_destructor;
1159 p = (f * CD_FRAMESIZE) / PAGE_SIZE;
1160 offset = (f * CD_FRAMESIZE) % PAGE_SIZE;
1161 VPRINTK("pkt_gather_data: Adding frame %d, page:%p offs:%d\n",
1162 f, pkt->pages[p], offset);
1163 if (!bio_add_page(bio, pkt->pages[p], CD_FRAMESIZE, offset))
1164 BUG();
1166 atomic_inc(&pkt->io_wait);
1167 bio->bi_rw = READ;
1168 pkt_queue_bio(pd, bio);
1169 frames_read++;
1172 out_account:
1173 VPRINTK("pkt_gather_data: need %d frames for zone %llx\n",
1174 frames_read, (unsigned long long)pkt->sector);
1175 pd->stats.pkt_started++;
1176 pd->stats.secs_rg += frames_read * (CD_FRAMESIZE >> 9);
1180 * Find a packet matching zone, or the least recently used packet if
1181 * there is no match.
1183 static struct packet_data *pkt_get_packet_data(struct pktcdvd_device *pd, int zone)
1185 struct packet_data *pkt;
1187 list_for_each_entry(pkt, &pd->cdrw.pkt_free_list, list) {
1188 if (pkt->sector == zone || pkt->list.next == &pd->cdrw.pkt_free_list) {
1189 list_del_init(&pkt->list);
1190 if (pkt->sector != zone)
1191 pkt->cache_valid = 0;
1192 return pkt;
1195 BUG();
1196 return NULL;
1199 static void pkt_put_packet_data(struct pktcdvd_device *pd, struct packet_data *pkt)
1201 if (pkt->cache_valid) {
1202 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
1203 } else {
1204 list_add_tail(&pkt->list, &pd->cdrw.pkt_free_list);
1209 * recover a failed write, query for relocation if possible
1211 * returns 1 if recovery is possible, or 0 if not
1214 static int pkt_start_recovery(struct packet_data *pkt)
1217 * FIXME. We need help from the file system to implement
1218 * recovery handling.
1220 return 0;
1221 #if 0
1222 struct request *rq = pkt->rq;
1223 struct pktcdvd_device *pd = rq->rq_disk->private_data;
1224 struct block_device *pkt_bdev;
1225 struct super_block *sb = NULL;
1226 unsigned long old_block, new_block;
1227 sector_t new_sector;
1229 pkt_bdev = bdget(kdev_t_to_nr(pd->pkt_dev));
1230 if (pkt_bdev) {
1231 sb = get_super(pkt_bdev);
1232 bdput(pkt_bdev);
1235 if (!sb)
1236 return 0;
1238 if (!sb->s_op || !sb->s_op->relocate_blocks)
1239 goto out;
1241 old_block = pkt->sector / (CD_FRAMESIZE >> 9);
1242 if (sb->s_op->relocate_blocks(sb, old_block, &new_block))
1243 goto out;
1245 new_sector = new_block * (CD_FRAMESIZE >> 9);
1246 pkt->sector = new_sector;
1248 pkt->bio->bi_sector = new_sector;
1249 pkt->bio->bi_next = NULL;
1250 pkt->bio->bi_flags = 1 << BIO_UPTODATE;
1251 pkt->bio->bi_idx = 0;
1253 BUG_ON(pkt->bio->bi_rw != (1 << BIO_RW));
1254 BUG_ON(pkt->bio->bi_vcnt != pkt->frames);
1255 BUG_ON(pkt->bio->bi_size != pkt->frames * CD_FRAMESIZE);
1256 BUG_ON(pkt->bio->bi_end_io != pkt_end_io_packet_write);
1257 BUG_ON(pkt->bio->bi_private != pkt);
1259 drop_super(sb);
1260 return 1;
1262 out:
1263 drop_super(sb);
1264 return 0;
1265 #endif
1268 static inline void pkt_set_state(struct packet_data *pkt, enum packet_data_state state)
1270 #if PACKET_DEBUG > 1
1271 static const char *state_name[] = {
1272 "IDLE", "WAITING", "READ_WAIT", "WRITE_WAIT", "RECOVERY", "FINISHED"
1274 enum packet_data_state old_state = pkt->state;
1275 VPRINTK("pkt %2d : s=%6llx %s -> %s\n", pkt->id, (unsigned long long)pkt->sector,
1276 state_name[old_state], state_name[state]);
1277 #endif
1278 pkt->state = state;
1282 * Scan the work queue to see if we can start a new packet.
1283 * returns non-zero if any work was done.
1285 static int pkt_handle_queue(struct pktcdvd_device *pd)
1287 struct packet_data *pkt, *p;
1288 struct bio *bio = NULL;
1289 sector_t zone = 0; /* Suppress gcc warning */
1290 struct pkt_rb_node *node, *first_node;
1291 struct rb_node *n;
1292 int wakeup;
1294 VPRINTK("handle_queue\n");
1296 atomic_set(&pd->scan_queue, 0);
1298 if (list_empty(&pd->cdrw.pkt_free_list)) {
1299 VPRINTK("handle_queue: no pkt\n");
1300 return 0;
1304 * Try to find a zone we are not already working on.
1306 spin_lock(&pd->lock);
1307 first_node = pkt_rbtree_find(pd, pd->current_sector);
1308 if (!first_node) {
1309 n = rb_first(&pd->bio_queue);
1310 if (n)
1311 first_node = rb_entry(n, struct pkt_rb_node, rb_node);
1313 node = first_node;
1314 while (node) {
1315 bio = node->bio;
1316 zone = ZONE(bio->bi_sector, pd);
1317 list_for_each_entry(p, &pd->cdrw.pkt_active_list, list) {
1318 if (p->sector == zone) {
1319 bio = NULL;
1320 goto try_next_bio;
1323 break;
1324 try_next_bio:
1325 node = pkt_rbtree_next(node);
1326 if (!node) {
1327 n = rb_first(&pd->bio_queue);
1328 if (n)
1329 node = rb_entry(n, struct pkt_rb_node, rb_node);
1331 if (node == first_node)
1332 node = NULL;
1334 spin_unlock(&pd->lock);
1335 if (!bio) {
1336 VPRINTK("handle_queue: no bio\n");
1337 return 0;
1340 pkt = pkt_get_packet_data(pd, zone);
1342 pd->current_sector = zone + pd->settings.size;
1343 pkt->sector = zone;
1344 BUG_ON(pkt->frames != pd->settings.size >> 2);
1345 pkt->write_size = 0;
1348 * Scan work queue for bios in the same zone and link them
1349 * to this packet.
1351 spin_lock(&pd->lock);
1352 VPRINTK("pkt_handle_queue: looking for zone %llx\n", (unsigned long long)zone);
1353 while ((node = pkt_rbtree_find(pd, zone)) != NULL) {
1354 bio = node->bio;
1355 VPRINTK("pkt_handle_queue: found zone=%llx\n",
1356 (unsigned long long)ZONE(bio->bi_sector, pd));
1357 if (ZONE(bio->bi_sector, pd) != zone)
1358 break;
1359 pkt_rbtree_erase(pd, node);
1360 spin_lock(&pkt->lock);
1361 pkt_add_list_last(bio, &pkt->orig_bios, &pkt->orig_bios_tail);
1362 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
1363 spin_unlock(&pkt->lock);
1365 /* check write congestion marks, and if bio_queue_size is
1366 below, wake up any waiters */
1367 wakeup = (pd->write_congestion_on > 0
1368 && pd->bio_queue_size <= pd->write_congestion_off);
1369 spin_unlock(&pd->lock);
1370 if (wakeup)
1371 clear_bdi_congested(&pd->disk->queue->backing_dev_info, WRITE);
1373 pkt->sleep_time = max(PACKET_WAIT_TIME, 1);
1374 pkt_set_state(pkt, PACKET_WAITING_STATE);
1375 atomic_set(&pkt->run_sm, 1);
1377 spin_lock(&pd->cdrw.active_list_lock);
1378 list_add(&pkt->list, &pd->cdrw.pkt_active_list);
1379 spin_unlock(&pd->cdrw.active_list_lock);
1381 return 1;
1385 * Assemble a bio to write one packet and queue the bio for processing
1386 * by the underlying block device.
1388 static void pkt_start_write(struct pktcdvd_device *pd, struct packet_data *pkt)
1390 struct bio *bio;
1391 int f;
1392 int frames_write;
1393 struct bio_vec *bvec = pkt->w_bio->bi_io_vec;
1395 for (f = 0; f < pkt->frames; f++) {
1396 bvec[f].bv_page = pkt->pages[(f * CD_FRAMESIZE) / PAGE_SIZE];
1397 bvec[f].bv_offset = (f * CD_FRAMESIZE) % PAGE_SIZE;
1401 * Fill-in bvec with data from orig_bios.
1403 frames_write = 0;
1404 spin_lock(&pkt->lock);
1405 for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
1406 int segment = bio->bi_idx;
1407 int src_offs = 0;
1408 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
1409 int num_frames = bio->bi_size / CD_FRAMESIZE;
1410 BUG_ON(first_frame < 0);
1411 BUG_ON(first_frame + num_frames > pkt->frames);
1412 for (f = first_frame; f < first_frame + num_frames; f++) {
1413 struct bio_vec *src_bvl = bio_iovec_idx(bio, segment);
1415 while (src_offs >= src_bvl->bv_len) {
1416 src_offs -= src_bvl->bv_len;
1417 segment++;
1418 BUG_ON(segment >= bio->bi_vcnt);
1419 src_bvl = bio_iovec_idx(bio, segment);
1422 if (src_bvl->bv_len - src_offs >= CD_FRAMESIZE) {
1423 bvec[f].bv_page = src_bvl->bv_page;
1424 bvec[f].bv_offset = src_bvl->bv_offset + src_offs;
1425 } else {
1426 pkt_copy_bio_data(bio, segment, src_offs,
1427 bvec[f].bv_page, bvec[f].bv_offset);
1429 src_offs += CD_FRAMESIZE;
1430 frames_write++;
1433 pkt_set_state(pkt, PACKET_WRITE_WAIT_STATE);
1434 spin_unlock(&pkt->lock);
1436 VPRINTK("pkt_start_write: Writing %d frames for zone %llx\n",
1437 frames_write, (unsigned long long)pkt->sector);
1438 BUG_ON(frames_write != pkt->write_size);
1440 if (test_bit(PACKET_MERGE_SEGS, &pd->flags) || (pkt->write_size < pkt->frames)) {
1441 pkt_make_local_copy(pkt, bvec);
1442 pkt->cache_valid = 1;
1443 } else {
1444 pkt->cache_valid = 0;
1447 /* Start the write request */
1448 bio_init(pkt->w_bio);
1449 pkt->w_bio->bi_max_vecs = PACKET_MAX_SIZE;
1450 pkt->w_bio->bi_sector = pkt->sector;
1451 pkt->w_bio->bi_bdev = pd->bdev;
1452 pkt->w_bio->bi_end_io = pkt_end_io_packet_write;
1453 pkt->w_bio->bi_private = pkt;
1454 pkt->w_bio->bi_io_vec = bvec;
1455 pkt->w_bio->bi_destructor = pkt_bio_destructor;
1456 for (f = 0; f < pkt->frames; f++)
1457 if (!bio_add_page(pkt->w_bio, bvec[f].bv_page, CD_FRAMESIZE, bvec[f].bv_offset))
1458 BUG();
1459 VPRINTK(DRIVER_NAME": vcnt=%d\n", pkt->w_bio->bi_vcnt);
1461 atomic_set(&pkt->io_wait, 1);
1462 pkt->w_bio->bi_rw = WRITE;
1463 pkt_queue_bio(pd, pkt->w_bio);
1466 static void pkt_finish_packet(struct packet_data *pkt, int uptodate)
1468 struct bio *bio, *next;
1470 if (!uptodate)
1471 pkt->cache_valid = 0;
1473 /* Finish all bios corresponding to this packet */
1474 bio = pkt->orig_bios;
1475 while (bio) {
1476 next = bio->bi_next;
1477 bio->bi_next = NULL;
1478 bio_endio(bio, uptodate ? 0 : -EIO);
1479 bio = next;
1481 pkt->orig_bios = pkt->orig_bios_tail = NULL;
1484 static void pkt_run_state_machine(struct pktcdvd_device *pd, struct packet_data *pkt)
1486 int uptodate;
1488 VPRINTK("run_state_machine: pkt %d\n", pkt->id);
1490 for (;;) {
1491 switch (pkt->state) {
1492 case PACKET_WAITING_STATE:
1493 if ((pkt->write_size < pkt->frames) && (pkt->sleep_time > 0))
1494 return;
1496 pkt->sleep_time = 0;
1497 pkt_gather_data(pd, pkt);
1498 pkt_set_state(pkt, PACKET_READ_WAIT_STATE);
1499 break;
1501 case PACKET_READ_WAIT_STATE:
1502 if (atomic_read(&pkt->io_wait) > 0)
1503 return;
1505 if (atomic_read(&pkt->io_errors) > 0) {
1506 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1507 } else {
1508 pkt_start_write(pd, pkt);
1510 break;
1512 case PACKET_WRITE_WAIT_STATE:
1513 if (atomic_read(&pkt->io_wait) > 0)
1514 return;
1516 if (test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags)) {
1517 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1518 } else {
1519 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1521 break;
1523 case PACKET_RECOVERY_STATE:
1524 if (pkt_start_recovery(pkt)) {
1525 pkt_start_write(pd, pkt);
1526 } else {
1527 VPRINTK("No recovery possible\n");
1528 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1530 break;
1532 case PACKET_FINISHED_STATE:
1533 uptodate = test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags);
1534 pkt_finish_packet(pkt, uptodate);
1535 return;
1537 default:
1538 BUG();
1539 break;
1544 static void pkt_handle_packets(struct pktcdvd_device *pd)
1546 struct packet_data *pkt, *next;
1548 VPRINTK("pkt_handle_packets\n");
1551 * Run state machine for active packets
1553 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1554 if (atomic_read(&pkt->run_sm) > 0) {
1555 atomic_set(&pkt->run_sm, 0);
1556 pkt_run_state_machine(pd, pkt);
1561 * Move no longer active packets to the free list
1563 spin_lock(&pd->cdrw.active_list_lock);
1564 list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_active_list, list) {
1565 if (pkt->state == PACKET_FINISHED_STATE) {
1566 list_del(&pkt->list);
1567 pkt_put_packet_data(pd, pkt);
1568 pkt_set_state(pkt, PACKET_IDLE_STATE);
1569 atomic_set(&pd->scan_queue, 1);
1572 spin_unlock(&pd->cdrw.active_list_lock);
1575 static void pkt_count_states(struct pktcdvd_device *pd, int *states)
1577 struct packet_data *pkt;
1578 int i;
1580 for (i = 0; i < PACKET_NUM_STATES; i++)
1581 states[i] = 0;
1583 spin_lock(&pd->cdrw.active_list_lock);
1584 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1585 states[pkt->state]++;
1587 spin_unlock(&pd->cdrw.active_list_lock);
1591 * kcdrwd is woken up when writes have been queued for one of our
1592 * registered devices
1594 static int kcdrwd(void *foobar)
1596 struct pktcdvd_device *pd = foobar;
1597 struct packet_data *pkt;
1598 long min_sleep_time, residue;
1600 set_user_nice(current, -20);
1601 set_freezable();
1603 for (;;) {
1604 DECLARE_WAITQUEUE(wait, current);
1607 * Wait until there is something to do
1609 add_wait_queue(&pd->wqueue, &wait);
1610 for (;;) {
1611 set_current_state(TASK_INTERRUPTIBLE);
1613 /* Check if we need to run pkt_handle_queue */
1614 if (atomic_read(&pd->scan_queue) > 0)
1615 goto work_to_do;
1617 /* Check if we need to run the state machine for some packet */
1618 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1619 if (atomic_read(&pkt->run_sm) > 0)
1620 goto work_to_do;
1623 /* Check if we need to process the iosched queues */
1624 if (atomic_read(&pd->iosched.attention) != 0)
1625 goto work_to_do;
1627 /* Otherwise, go to sleep */
1628 if (PACKET_DEBUG > 1) {
1629 int states[PACKET_NUM_STATES];
1630 pkt_count_states(pd, states);
1631 VPRINTK("kcdrwd: i:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
1632 states[0], states[1], states[2], states[3],
1633 states[4], states[5]);
1636 min_sleep_time = MAX_SCHEDULE_TIMEOUT;
1637 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1638 if (pkt->sleep_time && pkt->sleep_time < min_sleep_time)
1639 min_sleep_time = pkt->sleep_time;
1642 generic_unplug_device(bdev_get_queue(pd->bdev));
1644 VPRINTK("kcdrwd: sleeping\n");
1645 residue = schedule_timeout(min_sleep_time);
1646 VPRINTK("kcdrwd: wake up\n");
1648 /* make swsusp happy with our thread */
1649 try_to_freeze();
1651 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1652 if (!pkt->sleep_time)
1653 continue;
1654 pkt->sleep_time -= min_sleep_time - residue;
1655 if (pkt->sleep_time <= 0) {
1656 pkt->sleep_time = 0;
1657 atomic_inc(&pkt->run_sm);
1661 if (kthread_should_stop())
1662 break;
1664 work_to_do:
1665 set_current_state(TASK_RUNNING);
1666 remove_wait_queue(&pd->wqueue, &wait);
1668 if (kthread_should_stop())
1669 break;
1672 * if pkt_handle_queue returns true, we can queue
1673 * another request.
1675 while (pkt_handle_queue(pd))
1679 * Handle packet state machine
1681 pkt_handle_packets(pd);
1684 * Handle iosched queues
1686 pkt_iosched_process_queue(pd);
1689 return 0;
1692 static void pkt_print_settings(struct pktcdvd_device *pd)
1694 printk(DRIVER_NAME": %s packets, ", pd->settings.fp ? "Fixed" : "Variable");
1695 printk("%u blocks, ", pd->settings.size >> 2);
1696 printk("Mode-%c disc\n", pd->settings.block_mode == 8 ? '1' : '2');
1699 static int pkt_mode_sense(struct pktcdvd_device *pd, struct packet_command *cgc, int page_code, int page_control)
1701 memset(cgc->cmd, 0, sizeof(cgc->cmd));
1703 cgc->cmd[0] = GPCMD_MODE_SENSE_10;
1704 cgc->cmd[2] = page_code | (page_control << 6);
1705 cgc->cmd[7] = cgc->buflen >> 8;
1706 cgc->cmd[8] = cgc->buflen & 0xff;
1707 cgc->data_direction = CGC_DATA_READ;
1708 return pkt_generic_packet(pd, cgc);
1711 static int pkt_mode_select(struct pktcdvd_device *pd, struct packet_command *cgc)
1713 memset(cgc->cmd, 0, sizeof(cgc->cmd));
1714 memset(cgc->buffer, 0, 2);
1715 cgc->cmd[0] = GPCMD_MODE_SELECT_10;
1716 cgc->cmd[1] = 0x10; /* PF */
1717 cgc->cmd[7] = cgc->buflen >> 8;
1718 cgc->cmd[8] = cgc->buflen & 0xff;
1719 cgc->data_direction = CGC_DATA_WRITE;
1720 return pkt_generic_packet(pd, cgc);
1723 static int pkt_get_disc_info(struct pktcdvd_device *pd, disc_information *di)
1725 struct packet_command cgc;
1726 int ret;
1728 /* set up command and get the disc info */
1729 init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);
1730 cgc.cmd[0] = GPCMD_READ_DISC_INFO;
1731 cgc.cmd[8] = cgc.buflen = 2;
1732 cgc.quiet = 1;
1734 if ((ret = pkt_generic_packet(pd, &cgc)))
1735 return ret;
1737 /* not all drives have the same disc_info length, so requeue
1738 * packet with the length the drive tells us it can supply
1740 cgc.buflen = be16_to_cpu(di->disc_information_length) +
1741 sizeof(di->disc_information_length);
1743 if (cgc.buflen > sizeof(disc_information))
1744 cgc.buflen = sizeof(disc_information);
1746 cgc.cmd[8] = cgc.buflen;
1747 return pkt_generic_packet(pd, &cgc);
1750 static int pkt_get_track_info(struct pktcdvd_device *pd, __u16 track, __u8 type, track_information *ti)
1752 struct packet_command cgc;
1753 int ret;
1755 init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);
1756 cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;
1757 cgc.cmd[1] = type & 3;
1758 cgc.cmd[4] = (track & 0xff00) >> 8;
1759 cgc.cmd[5] = track & 0xff;
1760 cgc.cmd[8] = 8;
1761 cgc.quiet = 1;
1763 if ((ret = pkt_generic_packet(pd, &cgc)))
1764 return ret;
1766 cgc.buflen = be16_to_cpu(ti->track_information_length) +
1767 sizeof(ti->track_information_length);
1769 if (cgc.buflen > sizeof(track_information))
1770 cgc.buflen = sizeof(track_information);
1772 cgc.cmd[8] = cgc.buflen;
1773 return pkt_generic_packet(pd, &cgc);
1776 static int pkt_get_last_written(struct pktcdvd_device *pd, long *last_written)
1778 disc_information di;
1779 track_information ti;
1780 __u32 last_track;
1781 int ret = -1;
1783 if ((ret = pkt_get_disc_info(pd, &di)))
1784 return ret;
1786 last_track = (di.last_track_msb << 8) | di.last_track_lsb;
1787 if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1788 return ret;
1790 /* if this track is blank, try the previous. */
1791 if (ti.blank) {
1792 last_track--;
1793 if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1794 return ret;
1797 /* if last recorded field is valid, return it. */
1798 if (ti.lra_v) {
1799 *last_written = be32_to_cpu(ti.last_rec_address);
1800 } else {
1801 /* make it up instead */
1802 *last_written = be32_to_cpu(ti.track_start) +
1803 be32_to_cpu(ti.track_size);
1804 if (ti.free_blocks)
1805 *last_written -= (be32_to_cpu(ti.free_blocks) + 7);
1807 return 0;
1811 * write mode select package based on pd->settings
1813 static int pkt_set_write_settings(struct pktcdvd_device *pd)
1815 struct packet_command cgc;
1816 struct request_sense sense;
1817 write_param_page *wp;
1818 char buffer[128];
1819 int ret, size;
1821 /* doesn't apply to DVD+RW or DVD-RAM */
1822 if ((pd->mmc3_profile == 0x1a) || (pd->mmc3_profile == 0x12))
1823 return 0;
1825 memset(buffer, 0, sizeof(buffer));
1826 init_cdrom_command(&cgc, buffer, sizeof(*wp), CGC_DATA_READ);
1827 cgc.sense = &sense;
1828 if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1829 pkt_dump_sense(&cgc);
1830 return ret;
1833 size = 2 + ((buffer[0] << 8) | (buffer[1] & 0xff));
1834 pd->mode_offset = (buffer[6] << 8) | (buffer[7] & 0xff);
1835 if (size > sizeof(buffer))
1836 size = sizeof(buffer);
1839 * now get it all
1841 init_cdrom_command(&cgc, buffer, size, CGC_DATA_READ);
1842 cgc.sense = &sense;
1843 if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1844 pkt_dump_sense(&cgc);
1845 return ret;
1849 * write page is offset header + block descriptor length
1851 wp = (write_param_page *) &buffer[sizeof(struct mode_page_header) + pd->mode_offset];
1853 wp->fp = pd->settings.fp;
1854 wp->track_mode = pd->settings.track_mode;
1855 wp->write_type = pd->settings.write_type;
1856 wp->data_block_type = pd->settings.block_mode;
1858 wp->multi_session = 0;
1860 #ifdef PACKET_USE_LS
1861 wp->link_size = 7;
1862 wp->ls_v = 1;
1863 #endif
1865 if (wp->data_block_type == PACKET_BLOCK_MODE1) {
1866 wp->session_format = 0;
1867 wp->subhdr2 = 0x20;
1868 } else if (wp->data_block_type == PACKET_BLOCK_MODE2) {
1869 wp->session_format = 0x20;
1870 wp->subhdr2 = 8;
1871 #if 0
1872 wp->mcn[0] = 0x80;
1873 memcpy(&wp->mcn[1], PACKET_MCN, sizeof(wp->mcn) - 1);
1874 #endif
1875 } else {
1877 * paranoia
1879 printk(DRIVER_NAME": write mode wrong %d\n", wp->data_block_type);
1880 return 1;
1882 wp->packet_size = cpu_to_be32(pd->settings.size >> 2);
1884 cgc.buflen = cgc.cmd[8] = size;
1885 if ((ret = pkt_mode_select(pd, &cgc))) {
1886 pkt_dump_sense(&cgc);
1887 return ret;
1890 pkt_print_settings(pd);
1891 return 0;
1895 * 1 -- we can write to this track, 0 -- we can't
1897 static int pkt_writable_track(struct pktcdvd_device *pd, track_information *ti)
1899 switch (pd->mmc3_profile) {
1900 case 0x1a: /* DVD+RW */
1901 case 0x12: /* DVD-RAM */
1902 /* The track is always writable on DVD+RW/DVD-RAM */
1903 return 1;
1904 default:
1905 break;
1908 if (!ti->packet || !ti->fp)
1909 return 0;
1912 * "good" settings as per Mt Fuji.
1914 if (ti->rt == 0 && ti->blank == 0)
1915 return 1;
1917 if (ti->rt == 0 && ti->blank == 1)
1918 return 1;
1920 if (ti->rt == 1 && ti->blank == 0)
1921 return 1;
1923 printk(DRIVER_NAME": bad state %d-%d-%d\n", ti->rt, ti->blank, ti->packet);
1924 return 0;
1928 * 1 -- we can write to this disc, 0 -- we can't
1930 static int pkt_writable_disc(struct pktcdvd_device *pd, disc_information *di)
1932 switch (pd->mmc3_profile) {
1933 case 0x0a: /* CD-RW */
1934 case 0xffff: /* MMC3 not supported */
1935 break;
1936 case 0x1a: /* DVD+RW */
1937 case 0x13: /* DVD-RW */
1938 case 0x12: /* DVD-RAM */
1939 return 1;
1940 default:
1941 VPRINTK(DRIVER_NAME": Wrong disc profile (%x)\n", pd->mmc3_profile);
1942 return 0;
1946 * for disc type 0xff we should probably reserve a new track.
1947 * but i'm not sure, should we leave this to user apps? probably.
1949 if (di->disc_type == 0xff) {
1950 printk(DRIVER_NAME": Unknown disc. No track?\n");
1951 return 0;
1954 if (di->disc_type != 0x20 && di->disc_type != 0) {
1955 printk(DRIVER_NAME": Wrong disc type (%x)\n", di->disc_type);
1956 return 0;
1959 if (di->erasable == 0) {
1960 printk(DRIVER_NAME": Disc not erasable\n");
1961 return 0;
1964 if (di->border_status == PACKET_SESSION_RESERVED) {
1965 printk(DRIVER_NAME": Can't write to last track (reserved)\n");
1966 return 0;
1969 return 1;
1972 static int pkt_probe_settings(struct pktcdvd_device *pd)
1974 struct packet_command cgc;
1975 unsigned char buf[12];
1976 disc_information di;
1977 track_information ti;
1978 int ret, track;
1980 init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1981 cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
1982 cgc.cmd[8] = 8;
1983 ret = pkt_generic_packet(pd, &cgc);
1984 pd->mmc3_profile = ret ? 0xffff : buf[6] << 8 | buf[7];
1986 memset(&di, 0, sizeof(disc_information));
1987 memset(&ti, 0, sizeof(track_information));
1989 if ((ret = pkt_get_disc_info(pd, &di))) {
1990 printk("failed get_disc\n");
1991 return ret;
1994 if (!pkt_writable_disc(pd, &di))
1995 return -EROFS;
1997 pd->type = di.erasable ? PACKET_CDRW : PACKET_CDR;
1999 track = 1; /* (di.last_track_msb << 8) | di.last_track_lsb; */
2000 if ((ret = pkt_get_track_info(pd, track, 1, &ti))) {
2001 printk(DRIVER_NAME": failed get_track\n");
2002 return ret;
2005 if (!pkt_writable_track(pd, &ti)) {
2006 printk(DRIVER_NAME": can't write to this track\n");
2007 return -EROFS;
2011 * we keep packet size in 512 byte units, makes it easier to
2012 * deal with request calculations.
2014 pd->settings.size = be32_to_cpu(ti.fixed_packet_size) << 2;
2015 if (pd->settings.size == 0) {
2016 printk(DRIVER_NAME": detected zero packet size!\n");
2017 return -ENXIO;
2019 if (pd->settings.size > PACKET_MAX_SECTORS) {
2020 printk(DRIVER_NAME": packet size is too big\n");
2021 return -EROFS;
2023 pd->settings.fp = ti.fp;
2024 pd->offset = (be32_to_cpu(ti.track_start) << 2) & (pd->settings.size - 1);
2026 if (ti.nwa_v) {
2027 pd->nwa = be32_to_cpu(ti.next_writable);
2028 set_bit(PACKET_NWA_VALID, &pd->flags);
2032 * in theory we could use lra on -RW media as well and just zero
2033 * blocks that haven't been written yet, but in practice that
2034 * is just a no-go. we'll use that for -R, naturally.
2036 if (ti.lra_v) {
2037 pd->lra = be32_to_cpu(ti.last_rec_address);
2038 set_bit(PACKET_LRA_VALID, &pd->flags);
2039 } else {
2040 pd->lra = 0xffffffff;
2041 set_bit(PACKET_LRA_VALID, &pd->flags);
2045 * fine for now
2047 pd->settings.link_loss = 7;
2048 pd->settings.write_type = 0; /* packet */
2049 pd->settings.track_mode = ti.track_mode;
2052 * mode1 or mode2 disc
2054 switch (ti.data_mode) {
2055 case PACKET_MODE1:
2056 pd->settings.block_mode = PACKET_BLOCK_MODE1;
2057 break;
2058 case PACKET_MODE2:
2059 pd->settings.block_mode = PACKET_BLOCK_MODE2;
2060 break;
2061 default:
2062 printk(DRIVER_NAME": unknown data mode\n");
2063 return -EROFS;
2065 return 0;
2069 * enable/disable write caching on drive
2071 static int pkt_write_caching(struct pktcdvd_device *pd, int set)
2073 struct packet_command cgc;
2074 struct request_sense sense;
2075 unsigned char buf[64];
2076 int ret;
2078 memset(buf, 0, sizeof(buf));
2079 init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
2080 cgc.sense = &sense;
2081 cgc.buflen = pd->mode_offset + 12;
2084 * caching mode page might not be there, so quiet this command
2086 cgc.quiet = 1;
2088 if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WCACHING_PAGE, 0)))
2089 return ret;
2091 buf[pd->mode_offset + 10] |= (!!set << 2);
2093 cgc.buflen = cgc.cmd[8] = 2 + ((buf[0] << 8) | (buf[1] & 0xff));
2094 ret = pkt_mode_select(pd, &cgc);
2095 if (ret) {
2096 printk(DRIVER_NAME": write caching control failed\n");
2097 pkt_dump_sense(&cgc);
2098 } else if (!ret && set)
2099 printk(DRIVER_NAME": enabled write caching on %s\n", pd->name);
2100 return ret;
2103 static int pkt_lock_door(struct pktcdvd_device *pd, int lockflag)
2105 struct packet_command cgc;
2107 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
2108 cgc.cmd[0] = GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL;
2109 cgc.cmd[4] = lockflag ? 1 : 0;
2110 return pkt_generic_packet(pd, &cgc);
2114 * Returns drive maximum write speed
2116 static int pkt_get_max_speed(struct pktcdvd_device *pd, unsigned *write_speed)
2118 struct packet_command cgc;
2119 struct request_sense sense;
2120 unsigned char buf[256+18];
2121 unsigned char *cap_buf;
2122 int ret, offset;
2124 memset(buf, 0, sizeof(buf));
2125 cap_buf = &buf[sizeof(struct mode_page_header) + pd->mode_offset];
2126 init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_UNKNOWN);
2127 cgc.sense = &sense;
2129 ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
2130 if (ret) {
2131 cgc.buflen = pd->mode_offset + cap_buf[1] + 2 +
2132 sizeof(struct mode_page_header);
2133 ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
2134 if (ret) {
2135 pkt_dump_sense(&cgc);
2136 return ret;
2140 offset = 20; /* Obsoleted field, used by older drives */
2141 if (cap_buf[1] >= 28)
2142 offset = 28; /* Current write speed selected */
2143 if (cap_buf[1] >= 30) {
2144 /* If the drive reports at least one "Logical Unit Write
2145 * Speed Performance Descriptor Block", use the information
2146 * in the first block. (contains the highest speed)
2148 int num_spdb = (cap_buf[30] << 8) + cap_buf[31];
2149 if (num_spdb > 0)
2150 offset = 34;
2153 *write_speed = (cap_buf[offset] << 8) | cap_buf[offset + 1];
2154 return 0;
2157 /* These tables from cdrecord - I don't have orange book */
2158 /* standard speed CD-RW (1-4x) */
2159 static char clv_to_speed[16] = {
2160 /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
2161 0, 2, 4, 6, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
2163 /* high speed CD-RW (-10x) */
2164 static char hs_clv_to_speed[16] = {
2165 /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
2166 0, 2, 4, 6, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
2168 /* ultra high speed CD-RW */
2169 static char us_clv_to_speed[16] = {
2170 /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 */
2171 0, 2, 4, 8, 0, 0,16, 0,24,32,40,48, 0, 0, 0, 0
2175 * reads the maximum media speed from ATIP
2177 static int pkt_media_speed(struct pktcdvd_device *pd, unsigned *speed)
2179 struct packet_command cgc;
2180 struct request_sense sense;
2181 unsigned char buf[64];
2182 unsigned int size, st, sp;
2183 int ret;
2185 init_cdrom_command(&cgc, buf, 2, CGC_DATA_READ);
2186 cgc.sense = &sense;
2187 cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
2188 cgc.cmd[1] = 2;
2189 cgc.cmd[2] = 4; /* READ ATIP */
2190 cgc.cmd[8] = 2;
2191 ret = pkt_generic_packet(pd, &cgc);
2192 if (ret) {
2193 pkt_dump_sense(&cgc);
2194 return ret;
2196 size = ((unsigned int) buf[0]<<8) + buf[1] + 2;
2197 if (size > sizeof(buf))
2198 size = sizeof(buf);
2200 init_cdrom_command(&cgc, buf, size, CGC_DATA_READ);
2201 cgc.sense = &sense;
2202 cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
2203 cgc.cmd[1] = 2;
2204 cgc.cmd[2] = 4;
2205 cgc.cmd[8] = size;
2206 ret = pkt_generic_packet(pd, &cgc);
2207 if (ret) {
2208 pkt_dump_sense(&cgc);
2209 return ret;
2212 if (!(buf[6] & 0x40)) {
2213 printk(DRIVER_NAME": Disc type is not CD-RW\n");
2214 return 1;
2216 if (!(buf[6] & 0x4)) {
2217 printk(DRIVER_NAME": A1 values on media are not valid, maybe not CDRW?\n");
2218 return 1;
2221 st = (buf[6] >> 3) & 0x7; /* disc sub-type */
2223 sp = buf[16] & 0xf; /* max speed from ATIP A1 field */
2225 /* Info from cdrecord */
2226 switch (st) {
2227 case 0: /* standard speed */
2228 *speed = clv_to_speed[sp];
2229 break;
2230 case 1: /* high speed */
2231 *speed = hs_clv_to_speed[sp];
2232 break;
2233 case 2: /* ultra high speed */
2234 *speed = us_clv_to_speed[sp];
2235 break;
2236 default:
2237 printk(DRIVER_NAME": Unknown disc sub-type %d\n",st);
2238 return 1;
2240 if (*speed) {
2241 printk(DRIVER_NAME": Max. media speed: %d\n",*speed);
2242 return 0;
2243 } else {
2244 printk(DRIVER_NAME": Unknown speed %d for sub-type %d\n",sp,st);
2245 return 1;
2249 static int pkt_perform_opc(struct pktcdvd_device *pd)
2251 struct packet_command cgc;
2252 struct request_sense sense;
2253 int ret;
2255 VPRINTK(DRIVER_NAME": Performing OPC\n");
2257 init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
2258 cgc.sense = &sense;
2259 cgc.timeout = 60*HZ;
2260 cgc.cmd[0] = GPCMD_SEND_OPC;
2261 cgc.cmd[1] = 1;
2262 if ((ret = pkt_generic_packet(pd, &cgc)))
2263 pkt_dump_sense(&cgc);
2264 return ret;
2267 static int pkt_open_write(struct pktcdvd_device *pd)
2269 int ret;
2270 unsigned int write_speed, media_write_speed, read_speed;
2272 if ((ret = pkt_probe_settings(pd))) {
2273 VPRINTK(DRIVER_NAME": %s failed probe\n", pd->name);
2274 return ret;
2277 if ((ret = pkt_set_write_settings(pd))) {
2278 DPRINTK(DRIVER_NAME": %s failed saving write settings\n", pd->name);
2279 return -EIO;
2282 pkt_write_caching(pd, USE_WCACHING);
2284 if ((ret = pkt_get_max_speed(pd, &write_speed)))
2285 write_speed = 16 * 177;
2286 switch (pd->mmc3_profile) {
2287 case 0x13: /* DVD-RW */
2288 case 0x1a: /* DVD+RW */
2289 case 0x12: /* DVD-RAM */
2290 DPRINTK(DRIVER_NAME": write speed %ukB/s\n", write_speed);
2291 break;
2292 default:
2293 if ((ret = pkt_media_speed(pd, &media_write_speed)))
2294 media_write_speed = 16;
2295 write_speed = min(write_speed, media_write_speed * 177);
2296 DPRINTK(DRIVER_NAME": write speed %ux\n", write_speed / 176);
2297 break;
2299 read_speed = write_speed;
2301 if ((ret = pkt_set_speed(pd, write_speed, read_speed))) {
2302 DPRINTK(DRIVER_NAME": %s couldn't set write speed\n", pd->name);
2303 return -EIO;
2305 pd->write_speed = write_speed;
2306 pd->read_speed = read_speed;
2308 if ((ret = pkt_perform_opc(pd))) {
2309 DPRINTK(DRIVER_NAME": %s Optimum Power Calibration failed\n", pd->name);
2312 return 0;
2316 * called at open time.
2318 static int pkt_open_dev(struct pktcdvd_device *pd, int write)
2320 int ret;
2321 long lba;
2322 struct request_queue *q;
2325 * We need to re-open the cdrom device without O_NONBLOCK to be able
2326 * to read/write from/to it. It is already opened in O_NONBLOCK mode
2327 * so bdget() can't fail.
2329 bdget(pd->bdev->bd_dev);
2330 if ((ret = blkdev_get(pd->bdev, FMODE_READ, O_RDONLY)))
2331 goto out;
2333 if ((ret = bd_claim(pd->bdev, pd)))
2334 goto out_putdev;
2336 if ((ret = pkt_get_last_written(pd, &lba))) {
2337 printk(DRIVER_NAME": pkt_get_last_written failed\n");
2338 goto out_unclaim;
2341 set_capacity(pd->disk, lba << 2);
2342 set_capacity(pd->bdev->bd_disk, lba << 2);
2343 bd_set_size(pd->bdev, (loff_t)lba << 11);
2345 q = bdev_get_queue(pd->bdev);
2346 if (write) {
2347 if ((ret = pkt_open_write(pd)))
2348 goto out_unclaim;
2350 * Some CDRW drives can not handle writes larger than one packet,
2351 * even if the size is a multiple of the packet size.
2353 spin_lock_irq(q->queue_lock);
2354 blk_queue_max_sectors(q, pd->settings.size);
2355 spin_unlock_irq(q->queue_lock);
2356 set_bit(PACKET_WRITABLE, &pd->flags);
2357 } else {
2358 pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
2359 clear_bit(PACKET_WRITABLE, &pd->flags);
2362 if ((ret = pkt_set_segment_merging(pd, q)))
2363 goto out_unclaim;
2365 if (write) {
2366 if (!pkt_grow_pktlist(pd, CONFIG_CDROM_PKTCDVD_BUFFERS)) {
2367 printk(DRIVER_NAME": not enough memory for buffers\n");
2368 ret = -ENOMEM;
2369 goto out_unclaim;
2371 printk(DRIVER_NAME": %lukB available on disc\n", lba << 1);
2374 return 0;
2376 out_unclaim:
2377 bd_release(pd->bdev);
2378 out_putdev:
2379 blkdev_put(pd->bdev);
2380 out:
2381 return ret;
2385 * called when the device is closed. makes sure that the device flushes
2386 * the internal cache before we close.
2388 static void pkt_release_dev(struct pktcdvd_device *pd, int flush)
2390 if (flush && pkt_flush_cache(pd))
2391 DPRINTK(DRIVER_NAME": %s not flushing cache\n", pd->name);
2393 pkt_lock_door(pd, 0);
2395 pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
2396 bd_release(pd->bdev);
2397 blkdev_put(pd->bdev);
2399 pkt_shrink_pktlist(pd);
2402 static struct pktcdvd_device *pkt_find_dev_from_minor(int dev_minor)
2404 if (dev_minor >= MAX_WRITERS)
2405 return NULL;
2406 return pkt_devs[dev_minor];
2409 static int pkt_open(struct inode *inode, struct file *file)
2411 struct pktcdvd_device *pd = NULL;
2412 int ret;
2414 VPRINTK(DRIVER_NAME": entering open\n");
2416 mutex_lock(&ctl_mutex);
2417 pd = pkt_find_dev_from_minor(iminor(inode));
2418 if (!pd) {
2419 ret = -ENODEV;
2420 goto out;
2422 BUG_ON(pd->refcnt < 0);
2424 pd->refcnt++;
2425 if (pd->refcnt > 1) {
2426 if ((file->f_mode & FMODE_WRITE) &&
2427 !test_bit(PACKET_WRITABLE, &pd->flags)) {
2428 ret = -EBUSY;
2429 goto out_dec;
2431 } else {
2432 ret = pkt_open_dev(pd, file->f_mode & FMODE_WRITE);
2433 if (ret)
2434 goto out_dec;
2436 * needed here as well, since ext2 (among others) may change
2437 * the blocksize at mount time
2439 set_blocksize(inode->i_bdev, CD_FRAMESIZE);
2442 mutex_unlock(&ctl_mutex);
2443 return 0;
2445 out_dec:
2446 pd->refcnt--;
2447 out:
2448 VPRINTK(DRIVER_NAME": failed open (%d)\n", ret);
2449 mutex_unlock(&ctl_mutex);
2450 return ret;
2453 static int pkt_close(struct inode *inode, struct file *file)
2455 struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2456 int ret = 0;
2458 mutex_lock(&ctl_mutex);
2459 pd->refcnt--;
2460 BUG_ON(pd->refcnt < 0);
2461 if (pd->refcnt == 0) {
2462 int flush = test_bit(PACKET_WRITABLE, &pd->flags);
2463 pkt_release_dev(pd, flush);
2465 mutex_unlock(&ctl_mutex);
2466 return ret;
2470 static void pkt_end_io_read_cloned(struct bio *bio, int err)
2472 struct packet_stacked_data *psd = bio->bi_private;
2473 struct pktcdvd_device *pd = psd->pd;
2475 bio_put(bio);
2476 bio_endio(psd->bio, err);
2477 mempool_free(psd, psd_pool);
2478 pkt_bio_finished(pd);
2481 static int pkt_make_request(struct request_queue *q, struct bio *bio)
2483 struct pktcdvd_device *pd;
2484 char b[BDEVNAME_SIZE];
2485 sector_t zone;
2486 struct packet_data *pkt;
2487 int was_empty, blocked_bio;
2488 struct pkt_rb_node *node;
2490 pd = q->queuedata;
2491 if (!pd) {
2492 printk(DRIVER_NAME": %s incorrect request queue\n", bdevname(bio->bi_bdev, b));
2493 goto end_io;
2497 * Clone READ bios so we can have our own bi_end_io callback.
2499 if (bio_data_dir(bio) == READ) {
2500 struct bio *cloned_bio = bio_clone(bio, GFP_NOIO);
2501 struct packet_stacked_data *psd = mempool_alloc(psd_pool, GFP_NOIO);
2503 psd->pd = pd;
2504 psd->bio = bio;
2505 cloned_bio->bi_bdev = pd->bdev;
2506 cloned_bio->bi_private = psd;
2507 cloned_bio->bi_end_io = pkt_end_io_read_cloned;
2508 pd->stats.secs_r += bio->bi_size >> 9;
2509 pkt_queue_bio(pd, cloned_bio);
2510 return 0;
2513 if (!test_bit(PACKET_WRITABLE, &pd->flags)) {
2514 printk(DRIVER_NAME": WRITE for ro device %s (%llu)\n",
2515 pd->name, (unsigned long long)bio->bi_sector);
2516 goto end_io;
2519 if (!bio->bi_size || (bio->bi_size % CD_FRAMESIZE)) {
2520 printk(DRIVER_NAME": wrong bio size\n");
2521 goto end_io;
2524 blk_queue_bounce(q, &bio);
2526 zone = ZONE(bio->bi_sector, pd);
2527 VPRINTK("pkt_make_request: start = %6llx stop = %6llx\n",
2528 (unsigned long long)bio->bi_sector,
2529 (unsigned long long)(bio->bi_sector + bio_sectors(bio)));
2531 /* Check if we have to split the bio */
2533 struct bio_pair *bp;
2534 sector_t last_zone;
2535 int first_sectors;
2537 last_zone = ZONE(bio->bi_sector + bio_sectors(bio) - 1, pd);
2538 if (last_zone != zone) {
2539 BUG_ON(last_zone != zone + pd->settings.size);
2540 first_sectors = last_zone - bio->bi_sector;
2541 bp = bio_split(bio, bio_split_pool, first_sectors);
2542 BUG_ON(!bp);
2543 pkt_make_request(q, &bp->bio1);
2544 pkt_make_request(q, &bp->bio2);
2545 bio_pair_release(bp);
2546 return 0;
2551 * If we find a matching packet in state WAITING or READ_WAIT, we can
2552 * just append this bio to that packet.
2554 spin_lock(&pd->cdrw.active_list_lock);
2555 blocked_bio = 0;
2556 list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
2557 if (pkt->sector == zone) {
2558 spin_lock(&pkt->lock);
2559 if ((pkt->state == PACKET_WAITING_STATE) ||
2560 (pkt->state == PACKET_READ_WAIT_STATE)) {
2561 pkt_add_list_last(bio, &pkt->orig_bios,
2562 &pkt->orig_bios_tail);
2563 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
2564 if ((pkt->write_size >= pkt->frames) &&
2565 (pkt->state == PACKET_WAITING_STATE)) {
2566 atomic_inc(&pkt->run_sm);
2567 wake_up(&pd->wqueue);
2569 spin_unlock(&pkt->lock);
2570 spin_unlock(&pd->cdrw.active_list_lock);
2571 return 0;
2572 } else {
2573 blocked_bio = 1;
2575 spin_unlock(&pkt->lock);
2578 spin_unlock(&pd->cdrw.active_list_lock);
2581 * Test if there is enough room left in the bio work queue
2582 * (queue size >= congestion on mark).
2583 * If not, wait till the work queue size is below the congestion off mark.
2585 spin_lock(&pd->lock);
2586 if (pd->write_congestion_on > 0
2587 && pd->bio_queue_size >= pd->write_congestion_on) {
2588 set_bdi_congested(&q->backing_dev_info, WRITE);
2589 do {
2590 spin_unlock(&pd->lock);
2591 congestion_wait(WRITE, HZ);
2592 spin_lock(&pd->lock);
2593 } while(pd->bio_queue_size > pd->write_congestion_off);
2595 spin_unlock(&pd->lock);
2598 * No matching packet found. Store the bio in the work queue.
2600 node = mempool_alloc(pd->rb_pool, GFP_NOIO);
2601 node->bio = bio;
2602 spin_lock(&pd->lock);
2603 BUG_ON(pd->bio_queue_size < 0);
2604 was_empty = (pd->bio_queue_size == 0);
2605 pkt_rbtree_insert(pd, node);
2606 spin_unlock(&pd->lock);
2609 * Wake up the worker thread.
2611 atomic_set(&pd->scan_queue, 1);
2612 if (was_empty) {
2613 /* This wake_up is required for correct operation */
2614 wake_up(&pd->wqueue);
2615 } else if (!list_empty(&pd->cdrw.pkt_free_list) && !blocked_bio) {
2617 * This wake up is not required for correct operation,
2618 * but improves performance in some cases.
2620 wake_up(&pd->wqueue);
2622 return 0;
2623 end_io:
2624 bio_io_error(bio);
2625 return 0;
2630 static int pkt_merge_bvec(struct request_queue *q, struct bio *bio, struct bio_vec *bvec)
2632 struct pktcdvd_device *pd = q->queuedata;
2633 sector_t zone = ZONE(bio->bi_sector, pd);
2634 int used = ((bio->bi_sector - zone) << 9) + bio->bi_size;
2635 int remaining = (pd->settings.size << 9) - used;
2636 int remaining2;
2639 * A bio <= PAGE_SIZE must be allowed. If it crosses a packet
2640 * boundary, pkt_make_request() will split the bio.
2642 remaining2 = PAGE_SIZE - bio->bi_size;
2643 remaining = max(remaining, remaining2);
2645 BUG_ON(remaining < 0);
2646 return remaining;
2649 static void pkt_init_queue(struct pktcdvd_device *pd)
2651 struct request_queue *q = pd->disk->queue;
2653 blk_queue_make_request(q, pkt_make_request);
2654 blk_queue_hardsect_size(q, CD_FRAMESIZE);
2655 blk_queue_max_sectors(q, PACKET_MAX_SECTORS);
2656 blk_queue_merge_bvec(q, pkt_merge_bvec);
2657 q->queuedata = pd;
2660 static int pkt_seq_show(struct seq_file *m, void *p)
2662 struct pktcdvd_device *pd = m->private;
2663 char *msg;
2664 char bdev_buf[BDEVNAME_SIZE];
2665 int states[PACKET_NUM_STATES];
2667 seq_printf(m, "Writer %s mapped to %s:\n", pd->name,
2668 bdevname(pd->bdev, bdev_buf));
2670 seq_printf(m, "\nSettings:\n");
2671 seq_printf(m, "\tpacket size:\t\t%dkB\n", pd->settings.size / 2);
2673 if (pd->settings.write_type == 0)
2674 msg = "Packet";
2675 else
2676 msg = "Unknown";
2677 seq_printf(m, "\twrite type:\t\t%s\n", msg);
2679 seq_printf(m, "\tpacket type:\t\t%s\n", pd->settings.fp ? "Fixed" : "Variable");
2680 seq_printf(m, "\tlink loss:\t\t%d\n", pd->settings.link_loss);
2682 seq_printf(m, "\ttrack mode:\t\t%d\n", pd->settings.track_mode);
2684 if (pd->settings.block_mode == PACKET_BLOCK_MODE1)
2685 msg = "Mode 1";
2686 else if (pd->settings.block_mode == PACKET_BLOCK_MODE2)
2687 msg = "Mode 2";
2688 else
2689 msg = "Unknown";
2690 seq_printf(m, "\tblock mode:\t\t%s\n", msg);
2692 seq_printf(m, "\nStatistics:\n");
2693 seq_printf(m, "\tpackets started:\t%lu\n", pd->stats.pkt_started);
2694 seq_printf(m, "\tpackets ended:\t\t%lu\n", pd->stats.pkt_ended);
2695 seq_printf(m, "\twritten:\t\t%lukB\n", pd->stats.secs_w >> 1);
2696 seq_printf(m, "\tread gather:\t\t%lukB\n", pd->stats.secs_rg >> 1);
2697 seq_printf(m, "\tread:\t\t\t%lukB\n", pd->stats.secs_r >> 1);
2699 seq_printf(m, "\nMisc:\n");
2700 seq_printf(m, "\treference count:\t%d\n", pd->refcnt);
2701 seq_printf(m, "\tflags:\t\t\t0x%lx\n", pd->flags);
2702 seq_printf(m, "\tread speed:\t\t%ukB/s\n", pd->read_speed);
2703 seq_printf(m, "\twrite speed:\t\t%ukB/s\n", pd->write_speed);
2704 seq_printf(m, "\tstart offset:\t\t%lu\n", pd->offset);
2705 seq_printf(m, "\tmode page offset:\t%u\n", pd->mode_offset);
2707 seq_printf(m, "\nQueue state:\n");
2708 seq_printf(m, "\tbios queued:\t\t%d\n", pd->bio_queue_size);
2709 seq_printf(m, "\tbios pending:\t\t%d\n", atomic_read(&pd->cdrw.pending_bios));
2710 seq_printf(m, "\tcurrent sector:\t\t0x%llx\n", (unsigned long long)pd->current_sector);
2712 pkt_count_states(pd, states);
2713 seq_printf(m, "\tstate:\t\t\ti:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
2714 states[0], states[1], states[2], states[3], states[4], states[5]);
2716 seq_printf(m, "\twrite congestion marks:\toff=%d on=%d\n",
2717 pd->write_congestion_off,
2718 pd->write_congestion_on);
2719 return 0;
2722 static int pkt_seq_open(struct inode *inode, struct file *file)
2724 return single_open(file, pkt_seq_show, PDE(inode)->data);
2727 static const struct file_operations pkt_proc_fops = {
2728 .open = pkt_seq_open,
2729 .read = seq_read,
2730 .llseek = seq_lseek,
2731 .release = single_release
2734 static int pkt_new_dev(struct pktcdvd_device *pd, dev_t dev)
2736 int i;
2737 int ret = 0;
2738 char b[BDEVNAME_SIZE];
2739 struct proc_dir_entry *proc;
2740 struct block_device *bdev;
2742 if (pd->pkt_dev == dev) {
2743 printk(DRIVER_NAME": Recursive setup not allowed\n");
2744 return -EBUSY;
2746 for (i = 0; i < MAX_WRITERS; i++) {
2747 struct pktcdvd_device *pd2 = pkt_devs[i];
2748 if (!pd2)
2749 continue;
2750 if (pd2->bdev->bd_dev == dev) {
2751 printk(DRIVER_NAME": %s already setup\n", bdevname(pd2->bdev, b));
2752 return -EBUSY;
2754 if (pd2->pkt_dev == dev) {
2755 printk(DRIVER_NAME": Can't chain pktcdvd devices\n");
2756 return -EBUSY;
2760 bdev = bdget(dev);
2761 if (!bdev)
2762 return -ENOMEM;
2763 ret = blkdev_get(bdev, FMODE_READ, O_RDONLY | O_NONBLOCK);
2764 if (ret)
2765 return ret;
2767 /* This is safe, since we have a reference from open(). */
2768 __module_get(THIS_MODULE);
2770 pd->bdev = bdev;
2771 set_blocksize(bdev, CD_FRAMESIZE);
2773 pkt_init_queue(pd);
2775 atomic_set(&pd->cdrw.pending_bios, 0);
2776 pd->cdrw.thread = kthread_run(kcdrwd, pd, "%s", pd->name);
2777 if (IS_ERR(pd->cdrw.thread)) {
2778 printk(DRIVER_NAME": can't start kernel thread\n");
2779 ret = -ENOMEM;
2780 goto out_mem;
2783 proc = create_proc_entry(pd->name, 0, pkt_proc);
2784 if (proc) {
2785 proc->data = pd;
2786 proc->proc_fops = &pkt_proc_fops;
2788 DPRINTK(DRIVER_NAME": writer %s mapped to %s\n", pd->name, bdevname(bdev, b));
2789 return 0;
2791 out_mem:
2792 blkdev_put(bdev);
2793 /* This is safe: open() is still holding a reference. */
2794 module_put(THIS_MODULE);
2795 return ret;
2798 static int pkt_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2800 struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2802 VPRINTK("pkt_ioctl: cmd %x, dev %d:%d\n", cmd, imajor(inode), iminor(inode));
2804 switch (cmd) {
2806 * forward selected CDROM ioctls to CD-ROM, for UDF
2808 case CDROMMULTISESSION:
2809 case CDROMREADTOCENTRY:
2810 case CDROM_LAST_WRITTEN:
2811 case CDROM_SEND_PACKET:
2812 case SCSI_IOCTL_SEND_COMMAND:
2813 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2815 case CDROMEJECT:
2817 * The door gets locked when the device is opened, so we
2818 * have to unlock it or else the eject command fails.
2820 if (pd->refcnt == 1)
2821 pkt_lock_door(pd, 0);
2822 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2824 default:
2825 VPRINTK(DRIVER_NAME": Unknown ioctl for %s (%x)\n", pd->name, cmd);
2826 return -ENOTTY;
2829 return 0;
2832 static int pkt_media_changed(struct gendisk *disk)
2834 struct pktcdvd_device *pd = disk->private_data;
2835 struct gendisk *attached_disk;
2837 if (!pd)
2838 return 0;
2839 if (!pd->bdev)
2840 return 0;
2841 attached_disk = pd->bdev->bd_disk;
2842 if (!attached_disk)
2843 return 0;
2844 return attached_disk->fops->media_changed(attached_disk);
2847 static struct block_device_operations pktcdvd_ops = {
2848 .owner = THIS_MODULE,
2849 .open = pkt_open,
2850 .release = pkt_close,
2851 .ioctl = pkt_ioctl,
2852 .media_changed = pkt_media_changed,
2856 * Set up mapping from pktcdvd device to CD-ROM device.
2858 static int pkt_setup_dev(dev_t dev, dev_t* pkt_dev)
2860 int idx;
2861 int ret = -ENOMEM;
2862 struct pktcdvd_device *pd;
2863 struct gendisk *disk;
2865 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
2867 for (idx = 0; idx < MAX_WRITERS; idx++)
2868 if (!pkt_devs[idx])
2869 break;
2870 if (idx == MAX_WRITERS) {
2871 printk(DRIVER_NAME": max %d writers supported\n", MAX_WRITERS);
2872 ret = -EBUSY;
2873 goto out_mutex;
2876 pd = kzalloc(sizeof(struct pktcdvd_device), GFP_KERNEL);
2877 if (!pd)
2878 goto out_mutex;
2880 pd->rb_pool = mempool_create_kmalloc_pool(PKT_RB_POOL_SIZE,
2881 sizeof(struct pkt_rb_node));
2882 if (!pd->rb_pool)
2883 goto out_mem;
2885 INIT_LIST_HEAD(&pd->cdrw.pkt_free_list);
2886 INIT_LIST_HEAD(&pd->cdrw.pkt_active_list);
2887 spin_lock_init(&pd->cdrw.active_list_lock);
2889 spin_lock_init(&pd->lock);
2890 spin_lock_init(&pd->iosched.lock);
2891 sprintf(pd->name, DRIVER_NAME"%d", idx);
2892 init_waitqueue_head(&pd->wqueue);
2893 pd->bio_queue = RB_ROOT;
2895 pd->write_congestion_on = write_congestion_on;
2896 pd->write_congestion_off = write_congestion_off;
2898 disk = alloc_disk(1);
2899 if (!disk)
2900 goto out_mem;
2901 pd->disk = disk;
2902 disk->major = pktdev_major;
2903 disk->first_minor = idx;
2904 disk->fops = &pktcdvd_ops;
2905 disk->flags = GENHD_FL_REMOVABLE;
2906 strcpy(disk->disk_name, pd->name);
2907 disk->private_data = pd;
2908 disk->queue = blk_alloc_queue(GFP_KERNEL);
2909 if (!disk->queue)
2910 goto out_mem2;
2912 pd->pkt_dev = MKDEV(disk->major, disk->first_minor);
2913 ret = pkt_new_dev(pd, dev);
2914 if (ret)
2915 goto out_new_dev;
2917 add_disk(disk);
2919 pkt_sysfs_dev_new(pd);
2920 pkt_debugfs_dev_new(pd);
2922 pkt_devs[idx] = pd;
2923 if (pkt_dev)
2924 *pkt_dev = pd->pkt_dev;
2926 mutex_unlock(&ctl_mutex);
2927 return 0;
2929 out_new_dev:
2930 blk_cleanup_queue(disk->queue);
2931 out_mem2:
2932 put_disk(disk);
2933 out_mem:
2934 if (pd->rb_pool)
2935 mempool_destroy(pd->rb_pool);
2936 kfree(pd);
2937 out_mutex:
2938 mutex_unlock(&ctl_mutex);
2939 printk(DRIVER_NAME": setup of pktcdvd device failed\n");
2940 return ret;
2944 * Tear down mapping from pktcdvd device to CD-ROM device.
2946 static int pkt_remove_dev(dev_t pkt_dev)
2948 struct pktcdvd_device *pd;
2949 int idx;
2950 int ret = 0;
2952 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
2954 for (idx = 0; idx < MAX_WRITERS; idx++) {
2955 pd = pkt_devs[idx];
2956 if (pd && (pd->pkt_dev == pkt_dev))
2957 break;
2959 if (idx == MAX_WRITERS) {
2960 DPRINTK(DRIVER_NAME": dev not setup\n");
2961 ret = -ENXIO;
2962 goto out;
2965 if (pd->refcnt > 0) {
2966 ret = -EBUSY;
2967 goto out;
2969 if (!IS_ERR(pd->cdrw.thread))
2970 kthread_stop(pd->cdrw.thread);
2972 pkt_devs[idx] = NULL;
2974 pkt_debugfs_dev_remove(pd);
2975 pkt_sysfs_dev_remove(pd);
2977 blkdev_put(pd->bdev);
2979 remove_proc_entry(pd->name, pkt_proc);
2980 DPRINTK(DRIVER_NAME": writer %s unmapped\n", pd->name);
2982 del_gendisk(pd->disk);
2983 blk_cleanup_queue(pd->disk->queue);
2984 put_disk(pd->disk);
2986 mempool_destroy(pd->rb_pool);
2987 kfree(pd);
2989 /* This is safe: open() is still holding a reference. */
2990 module_put(THIS_MODULE);
2992 out:
2993 mutex_unlock(&ctl_mutex);
2994 return ret;
2997 static void pkt_get_status(struct pkt_ctrl_command *ctrl_cmd)
2999 struct pktcdvd_device *pd;
3001 mutex_lock_nested(&ctl_mutex, SINGLE_DEPTH_NESTING);
3003 pd = pkt_find_dev_from_minor(ctrl_cmd->dev_index);
3004 if (pd) {
3005 ctrl_cmd->dev = new_encode_dev(pd->bdev->bd_dev);
3006 ctrl_cmd->pkt_dev = new_encode_dev(pd->pkt_dev);
3007 } else {
3008 ctrl_cmd->dev = 0;
3009 ctrl_cmd->pkt_dev = 0;
3011 ctrl_cmd->num_devices = MAX_WRITERS;
3013 mutex_unlock(&ctl_mutex);
3016 static int pkt_ctl_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
3018 void __user *argp = (void __user *)arg;
3019 struct pkt_ctrl_command ctrl_cmd;
3020 int ret = 0;
3021 dev_t pkt_dev = 0;
3023 if (cmd != PACKET_CTRL_CMD)
3024 return -ENOTTY;
3026 if (copy_from_user(&ctrl_cmd, argp, sizeof(struct pkt_ctrl_command)))
3027 return -EFAULT;
3029 switch (ctrl_cmd.command) {
3030 case PKT_CTRL_CMD_SETUP:
3031 if (!capable(CAP_SYS_ADMIN))
3032 return -EPERM;
3033 ret = pkt_setup_dev(new_decode_dev(ctrl_cmd.dev), &pkt_dev);
3034 ctrl_cmd.pkt_dev = new_encode_dev(pkt_dev);
3035 break;
3036 case PKT_CTRL_CMD_TEARDOWN:
3037 if (!capable(CAP_SYS_ADMIN))
3038 return -EPERM;
3039 ret = pkt_remove_dev(new_decode_dev(ctrl_cmd.pkt_dev));
3040 break;
3041 case PKT_CTRL_CMD_STATUS:
3042 pkt_get_status(&ctrl_cmd);
3043 break;
3044 default:
3045 return -ENOTTY;
3048 if (copy_to_user(argp, &ctrl_cmd, sizeof(struct pkt_ctrl_command)))
3049 return -EFAULT;
3050 return ret;
3054 static const struct file_operations pkt_ctl_fops = {
3055 .ioctl = pkt_ctl_ioctl,
3056 .owner = THIS_MODULE,
3059 static struct miscdevice pkt_misc = {
3060 .minor = MISC_DYNAMIC_MINOR,
3061 .name = DRIVER_NAME,
3062 .fops = &pkt_ctl_fops
3065 static int __init pkt_init(void)
3067 int ret;
3069 mutex_init(&ctl_mutex);
3071 psd_pool = mempool_create_kmalloc_pool(PSD_POOL_SIZE,
3072 sizeof(struct packet_stacked_data));
3073 if (!psd_pool)
3074 return -ENOMEM;
3076 ret = register_blkdev(pktdev_major, DRIVER_NAME);
3077 if (ret < 0) {
3078 printk(DRIVER_NAME": Unable to register block device\n");
3079 goto out2;
3081 if (!pktdev_major)
3082 pktdev_major = ret;
3084 ret = pkt_sysfs_init();
3085 if (ret)
3086 goto out;
3088 pkt_debugfs_init();
3090 ret = misc_register(&pkt_misc);
3091 if (ret) {
3092 printk(DRIVER_NAME": Unable to register misc device\n");
3093 goto out_misc;
3096 pkt_proc = proc_mkdir(DRIVER_NAME, proc_root_driver);
3098 return 0;
3100 out_misc:
3101 pkt_debugfs_cleanup();
3102 pkt_sysfs_cleanup();
3103 out:
3104 unregister_blkdev(pktdev_major, DRIVER_NAME);
3105 out2:
3106 mempool_destroy(psd_pool);
3107 return ret;
3110 static void __exit pkt_exit(void)
3112 remove_proc_entry(DRIVER_NAME, proc_root_driver);
3113 misc_deregister(&pkt_misc);
3115 pkt_debugfs_cleanup();
3116 pkt_sysfs_cleanup();
3118 unregister_blkdev(pktdev_major, DRIVER_NAME);
3119 mempool_destroy(psd_pool);
3122 MODULE_DESCRIPTION("Packet writing layer for CD/DVD drives");
3123 MODULE_AUTHOR("Jens Axboe <axboe@suse.de>");
3124 MODULE_LICENSE("GPL");
3126 module_init(pkt_init);
3127 module_exit(pkt_exit);