Whamcloud - gitweb
15e4314b20cbb6126dc2955e6f141315e55bcd1b
[fs/lustre-release.git] / lustre / llite / lloop.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, Whamcloud, Inc.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 /*
38  *  linux/drivers/block/loop.c
39  *
40  *  Written by Theodore Ts'o, 3/29/93
41  *
42  * Copyright 1993 by Theodore Ts'o.  Redistribution of this file is
43  * permitted under the GNU General Public License.
44  *
45  * Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
46  * Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
47  *
48  * Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
49  *
50  * Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
51  *
52  * Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
53  *
54  * Loadable modules and other fixes by AK, 1998
55  *
56  * Maximum number of loop devices now dynamic via max_loop module parameter.
57  * Russell Kroll <rkroll@exploits.org> 19990701
58  *
59  * Maximum number of loop devices when compiled-in now selectable by passing
60  * max_loop=<1-255> to the kernel on boot.
61  * Erik I. Bols?, <eriki@himolde.no>, Oct 31, 1999
62  *
63  * Completely rewrite request handling to be make_request_fn style and
64  * non blocking, pushing work to a helper thread. Lots of fixes from
65  * Al Viro too.
66  * Jens Axboe <axboe@suse.de>, Nov 2000
67  *
68  * Support up to 256 loop devices
69  * Heinz Mauelshagen <mge@sistina.com>, Feb 2002
70  *
71  * Support for falling back on the write file operation when the address space
72  * operations prepare_write and/or commit_write are not available on the
73  * backing filesystem.
74  * Anton Altaparmakov, 16 Feb 2005
75  *
76  * Still To Fix:
77  * - Advisory locking is ignored here.
78  * - Should use an own CAP_* category instead of CAP_SYS_ADMIN
79  *
80  */
81
82 #ifndef AUTOCONF_INCLUDED
83 #include <linux/config.h>
84 #endif
85 #include <linux/module.h>
86
87 #include <linux/sched.h>
88 #include <linux/fs.h>
89 #include <linux/file.h>
90 #include <linux/stat.h>
91 #include <linux/errno.h>
92 #include <linux/major.h>
93 #include <linux/wait.h>
94 #include <linux/blkdev.h>
95 #include <linux/blkpg.h>
96 #include <linux/init.h>
97 #include <linux/smp_lock.h>
98 #include <linux/swap.h>
99 #include <linux/slab.h>
100 #include <linux/suspend.h>
101 #include <linux/writeback.h>
102 #include <linux/buffer_head.h>                /* for invalidate_bdev() */
103 #include <linux/completion.h>
104 #include <linux/highmem.h>
105 #include <linux/gfp.h>
106 #include <linux/swap.h>
107 #include <linux/pagevec.h>
108
109 #include <asm/uaccess.h>
110
111 #include <lustre_lib.h>
112 #include <lustre_lite.h>
113 #include "llite_internal.h"
114
115 #define LLOOP_MAX_SEGMENTS        PTLRPC_MAX_BRW_PAGES
116
117 /* Possible states of device */
118 enum {
119         LLOOP_UNBOUND,
120         LLOOP_BOUND,
121         LLOOP_RUNDOWN,
122 };
123
124 struct lloop_device {
125         int                  lo_number;
126         int                  lo_refcnt;
127         loff_t               lo_offset;
128         loff_t               lo_sizelimit;
129         int                  lo_flags;
130         int                (*ioctl)(struct lloop_device *, int cmd,
131                                     unsigned long arg);
132
133         struct file         *lo_backing_file;
134         struct block_device *lo_device;
135         unsigned             lo_blocksize;
136
137         int                  old_gfp_mask;
138
139         cfs_spinlock_t       lo_lock;
140         struct bio          *lo_bio;
141         struct bio          *lo_biotail;
142         int                  lo_state;
143         cfs_semaphore_t      lo_sem;
144         cfs_mutex_t          lo_ctl_mutex;
145         cfs_atomic_t         lo_pending;
146         cfs_waitq_t          lo_bh_wait;
147
148         struct request_queue *lo_queue;
149
150         const struct lu_env *lo_env;
151         struct cl_io         lo_io;
152         struct ll_dio_pages  lo_pvec;
153
154         /* data to handle bio for lustre. */
155         struct lo_request_data {
156                 struct page *lrd_pages[LLOOP_MAX_SEGMENTS];
157                 loff_t       lrd_offsets[LLOOP_MAX_SEGMENTS];
158         } lo_requests[1];
159 };
160
161 /*
162  * Loop flags
163  */
164 enum {
165         LO_FLAGS_READ_ONLY       = 1,
166 };
167
168 static int lloop_major;
169 #define MAX_LOOP_DEFAULT  16
170 static int max_loop = MAX_LOOP_DEFAULT;
171 static struct lloop_device *loop_dev;
172 static struct gendisk **disks;
173 static cfs_mutex_t lloop_mutex;
174 static void *ll_iocontrol_magic = NULL;
175
176 static loff_t get_loop_size(struct lloop_device *lo, struct file *file)
177 {
178         loff_t size, offset, loopsize;
179
180         /* Compute loopsize in bytes */
181         size = i_size_read(file->f_mapping->host);
182         offset = lo->lo_offset;
183         loopsize = size - offset;
184         if (lo->lo_sizelimit > 0 && lo->lo_sizelimit < loopsize)
185                 loopsize = lo->lo_sizelimit;
186
187         /*
188          * Unfortunately, if we want to do I/O on the device,
189          * the number of 512-byte sectors has to fit into a sector_t.
190          */
191         return loopsize >> 9;
192 }
193
194 static int do_bio_lustrebacked(struct lloop_device *lo, struct bio *head)
195 {
196         const struct lu_env  *env   = lo->lo_env;
197         struct cl_io         *io    = &lo->lo_io;
198         struct inode         *inode = lo->lo_backing_file->f_dentry->d_inode;
199         struct cl_object     *obj = ll_i2info(inode)->lli_clob;
200         pgoff_t               offset;
201         int                   ret;
202         int                   i;
203         int                   rw;
204         obd_count             page_count = 0;
205         struct bio_vec       *bvec;
206         struct bio           *bio;
207         ssize_t               bytes;
208
209         struct ll_dio_pages  *pvec = &lo->lo_pvec;
210         struct page         **pages = pvec->ldp_pages;
211         loff_t               *offsets = pvec->ldp_offsets;
212
213         truncate_inode_pages(inode->i_mapping, 0);
214
215         /* initialize the IO */
216         memset(io, 0, sizeof(*io));
217         io->ci_obj = obj;
218         ret = cl_io_init(env, io, CIT_MISC, obj);
219         if (ret)
220                 return io->ci_result;
221         io->ci_lockreq = CILR_NEVER;
222
223         LASSERT(head != NULL);
224         rw = head->bi_rw;
225         for (bio = head; bio != NULL; bio = bio->bi_next) {
226                 LASSERT(rw == bio->bi_rw);
227
228                 offset = (pgoff_t)(bio->bi_sector << 9) + lo->lo_offset;
229                 bio_for_each_segment(bvec, bio, i) {
230                         BUG_ON(bvec->bv_offset != 0);
231                         BUG_ON(bvec->bv_len != CFS_PAGE_SIZE);
232
233                         pages[page_count] = bvec->bv_page;
234                         offsets[page_count] = offset;
235                         page_count++;
236                         offset += bvec->bv_len;
237                 }
238                 LASSERT(page_count <= LLOOP_MAX_SEGMENTS);
239         }
240
241         ll_stats_ops_tally(ll_i2sbi(inode),
242                         (rw == WRITE) ? LPROC_LL_BRW_WRITE : LPROC_LL_BRW_READ,
243                         page_count);
244
245         pvec->ldp_size = page_count << PAGE_CACHE_SHIFT;
246         pvec->ldp_nr = page_count;
247
248         /* FIXME: in ll_direct_rw_pages, it has to allocate many cl_page{}s to
249          * write those pages into OST. Even worse case is that more pages
250          * would be asked to write out to swap space, and then finally get here
251          * again.
252          * Unfortunately this is NOT easy to fix.
253          * Thoughts on solution:
254          * 0. Define a reserved pool for cl_pages, which could be a list of
255          *    pre-allocated cl_pages from cl_page_kmem;
256          * 1. Define a new operation in cl_object_operations{}, says clo_depth,
257          *    which measures how many layers for this lustre object. Generally
258          *    speaking, the depth would be 2, one for llite, and one for lovsub.
259          *    However, for SNS, there will be more since we need additional page
260          *    to store parity;
261          * 2. Reserve the # of (page_count * depth) cl_pages from the reserved
262          *    pool. Afterwards, the clio would allocate the pages from reserved 
263          *    pool, this guarantees we neeedn't allocate the cl_pages from
264          *    generic cl_page slab cache.
265          *    Of course, if there is NOT enough pages in the pool, we might
266          *    be asked to write less pages once, this purely depends on
267          *    implementation. Anyway, we should be careful to avoid deadlocking.
268          */
269         LOCK_INODE_MUTEX(inode);
270         bytes = ll_direct_rw_pages(env, io, rw, inode, pvec);
271         UNLOCK_INODE_MUTEX(inode);
272         cl_io_fini(env, io);
273         return (bytes == pvec->ldp_size) ? 0 : (int)bytes;
274 }
275
276 /*
277  * Add bio to back of pending list
278  */
279 static void loop_add_bio(struct lloop_device *lo, struct bio *bio)
280 {
281         unsigned long flags;
282
283         cfs_spin_lock_irqsave(&lo->lo_lock, flags);
284         if (lo->lo_biotail) {
285                 lo->lo_biotail->bi_next = bio;
286                 lo->lo_biotail = bio;
287         } else
288                 lo->lo_bio = lo->lo_biotail = bio;
289         cfs_spin_unlock_irqrestore(&lo->lo_lock, flags);
290
291         cfs_atomic_inc(&lo->lo_pending);
292         if (cfs_waitq_active(&lo->lo_bh_wait))
293                 cfs_waitq_signal(&lo->lo_bh_wait);
294 }
295
296 /*
297  * Grab first pending buffer
298  */
299 static unsigned int loop_get_bio(struct lloop_device *lo, struct bio **req)
300 {
301         struct bio *first;
302         struct bio **bio;
303         unsigned int count = 0;
304         unsigned int page_count = 0;
305         int rw;
306
307         cfs_spin_lock_irq(&lo->lo_lock);
308         first = lo->lo_bio;
309         if (unlikely(first == NULL)) {
310                 cfs_spin_unlock_irq(&lo->lo_lock);
311                 return 0;
312         }
313
314         /* TODO: need to split the bio, too bad. */
315         LASSERT(first->bi_vcnt <= LLOOP_MAX_SEGMENTS);
316
317         rw = first->bi_rw;
318         bio = &lo->lo_bio;
319         while (*bio && (*bio)->bi_rw == rw) {
320                 CDEBUG(D_INFO, "bio sector %llu size %u count %u vcnt%u \n",
321                        (unsigned long long)(*bio)->bi_sector, (*bio)->bi_size,
322                        page_count, (*bio)->bi_vcnt);
323                 if (page_count + (*bio)->bi_vcnt > LLOOP_MAX_SEGMENTS)
324                         break;
325
326
327                 page_count += (*bio)->bi_vcnt;
328                 count++;
329                 bio = &(*bio)->bi_next;
330         }
331         if (*bio) {
332                 /* Some of bios can't be mergable. */
333                 lo->lo_bio = *bio;
334                 *bio = NULL;
335         } else {
336                 /* Hit the end of queue */
337                 lo->lo_biotail = NULL;
338                 lo->lo_bio = NULL;
339         }
340         *req = first;
341         cfs_spin_unlock_irq(&lo->lo_lock);
342         return count;
343 }
344
345 static int loop_make_request(struct request_queue *q, struct bio *old_bio)
346 {
347         struct lloop_device *lo = q->queuedata;
348         int rw = bio_rw(old_bio);
349         int inactive;
350
351         if (!lo)
352                 goto err;
353
354         CDEBUG(D_INFO, "submit bio sector %llu size %u\n",
355                (unsigned long long)old_bio->bi_sector, old_bio->bi_size);
356
357         cfs_spin_lock_irq(&lo->lo_lock);
358         inactive = (lo->lo_state != LLOOP_BOUND);
359         cfs_spin_unlock_irq(&lo->lo_lock);
360         if (inactive)
361                 goto err;
362
363         if (rw == WRITE) {
364                 if (lo->lo_flags & LO_FLAGS_READ_ONLY)
365                         goto err;
366         } else if (rw == READA) {
367                 rw = READ;
368         } else if (rw != READ) {
369                 CERROR("lloop: unknown command (%x)\n", rw);
370                 goto err;
371         }
372         loop_add_bio(lo, old_bio);
373         return 0;
374 err:
375         cfs_bio_io_error(old_bio, old_bio->bi_size);
376         return 0;
377 }
378
379 #ifdef HAVE_REQUEST_QUEUE_UNPLUG_FN
380 /*
381  * kick off io on the underlying address space
382  */
383 static void loop_unplug(struct request_queue *q)
384 {
385         struct lloop_device *lo = q->queuedata;
386
387         clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags);
388         blk_run_address_space(lo->lo_backing_file->f_mapping);
389 }
390 #endif
391
392 static inline void loop_handle_bio(struct lloop_device *lo, struct bio *bio)
393 {
394         int ret;
395         ret = do_bio_lustrebacked(lo, bio);
396         while (bio) {
397                 struct bio *tmp = bio->bi_next;
398                 bio->bi_next = NULL;
399                 cfs_bio_endio(bio, bio->bi_size, ret);
400                 bio = tmp;
401         }
402 }
403
404 static inline int loop_active(struct lloop_device *lo)
405 {
406         return cfs_atomic_read(&lo->lo_pending) ||
407                 (lo->lo_state == LLOOP_RUNDOWN);
408 }
409
410 /*
411  * worker thread that handles reads/writes to file backed loop devices,
412  * to avoid blocking in our make_request_fn.
413  */
414 static int loop_thread(void *data)
415 {
416         struct lloop_device *lo = data;
417         struct bio *bio;
418         unsigned int count;
419         unsigned long times = 0;
420         unsigned long total_count = 0;
421
422         struct lu_env *env;
423         int refcheck;
424         int ret = 0;
425
426         daemonize("lloop%d", lo->lo_number);
427
428         set_user_nice(current, -20);
429
430         lo->lo_state = LLOOP_BOUND;
431
432         env = cl_env_get(&refcheck);
433         if (IS_ERR(env))
434                 GOTO(out, ret = PTR_ERR(env));
435
436         lo->lo_env = env;
437         memset(&lo->lo_pvec, 0, sizeof(lo->lo_pvec));
438         lo->lo_pvec.ldp_pages   = lo->lo_requests[0].lrd_pages;
439         lo->lo_pvec.ldp_offsets = lo->lo_requests[0].lrd_offsets;
440
441         /*
442          * up sem, we are running
443          */
444         cfs_up(&lo->lo_sem);
445
446         for (;;) {
447                 cfs_wait_event(lo->lo_bh_wait, loop_active(lo));
448                 if (!cfs_atomic_read(&lo->lo_pending)) {
449                         int exiting = 0;
450                         cfs_spin_lock_irq(&lo->lo_lock);
451                         exiting = (lo->lo_state == LLOOP_RUNDOWN);
452                         cfs_spin_unlock_irq(&lo->lo_lock);
453                         if (exiting)
454                                 break;
455                 }
456
457                 bio = NULL;
458                 count = loop_get_bio(lo, &bio);
459                 if (!count) {
460                         CWARN("lloop(minor: %d): missing bio\n", lo->lo_number);
461                         continue;
462                 }
463
464                 total_count += count;
465                 if (total_count < count) {     /* overflow */
466                         total_count = count;
467                         times = 1;
468                 } else {
469                         times++;
470                 }
471                 if ((times & 127) == 0) {
472                         CDEBUG(D_INFO, "total: %lu, count: %lu, avg: %lu\n",
473                                total_count, times, total_count / times);
474                 }
475
476                 LASSERT(bio != NULL);
477                 LASSERT(count <= cfs_atomic_read(&lo->lo_pending));
478                 loop_handle_bio(lo, bio);
479                 cfs_atomic_sub(count, &lo->lo_pending);
480         }
481         cl_env_put(env, &refcheck);
482
483 out:
484         cfs_up(&lo->lo_sem);
485         return ret;
486 }
487
488 static int loop_set_fd(struct lloop_device *lo, struct file *unused,
489                        struct block_device *bdev, struct file *file)
490 {
491         struct inode         *inode;
492         struct address_space *mapping;
493         int                   lo_flags = 0;
494         int                   error;
495         loff_t                size;
496
497         if (!cfs_try_module_get(THIS_MODULE))
498                 return -ENODEV;
499
500         error = -EBUSY;
501         if (lo->lo_state != LLOOP_UNBOUND)
502                 goto out;
503
504         mapping = file->f_mapping;
505         inode = mapping->host;
506
507         error = -EINVAL;
508         if (!S_ISREG(inode->i_mode) || inode->i_sb->s_magic != LL_SUPER_MAGIC)
509                 goto out;
510
511         if (!(file->f_mode & FMODE_WRITE))
512                 lo_flags |= LO_FLAGS_READ_ONLY;
513
514         size = get_loop_size(lo, file);
515
516         if ((loff_t)(sector_t)size != size) {
517                 error = -EFBIG;
518                 goto out;
519         }
520
521         /* remove all pages in cache so as dirty pages not to be existent. */
522         truncate_inode_pages(mapping, 0);
523
524         set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
525
526         lo->lo_blocksize = CFS_PAGE_SIZE;
527         lo->lo_device = bdev;
528         lo->lo_flags = lo_flags;
529         lo->lo_backing_file = file;
530         lo->ioctl = NULL;
531         lo->lo_sizelimit = 0;
532         lo->old_gfp_mask = mapping_gfp_mask(mapping);
533         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
534
535         lo->lo_bio = lo->lo_biotail = NULL;
536
537         /*
538          * set queue make_request_fn, and add limits based on lower level
539          * device
540          */
541         blk_queue_make_request(lo->lo_queue, loop_make_request);
542         lo->lo_queue->queuedata = lo;
543 #ifdef HAVE_REQUEST_QUEUE_UNPLUG_FN
544         lo->lo_queue->unplug_fn = loop_unplug;
545 #endif
546
547         /* queue parameters */
548         CLASSERT(CFS_PAGE_SIZE < (1 << (sizeof(unsigned short) * 8)));
549         blk_queue_logical_block_size(lo->lo_queue,
550                                      (unsigned short)CFS_PAGE_SIZE);
551         blk_queue_max_hw_sectors(lo->lo_queue,
552                                  LLOOP_MAX_SEGMENTS << (CFS_PAGE_SHIFT - 9));
553         blk_queue_max_segments(lo->lo_queue, LLOOP_MAX_SEGMENTS);
554
555         set_capacity(disks[lo->lo_number], size);
556         bd_set_size(bdev, size << 9);
557
558         set_blocksize(bdev, lo->lo_blocksize);
559
560         cfs_create_thread(loop_thread, lo, CLONE_KERNEL);
561         cfs_down(&lo->lo_sem);
562         return 0;
563
564  out:
565         /* This is safe: open() is still holding a reference. */
566         cfs_module_put(THIS_MODULE);
567         return error;
568 }
569
570 static int loop_clr_fd(struct lloop_device *lo, struct block_device *bdev,
571                        int count)
572 {
573         struct file *filp = lo->lo_backing_file;
574         int gfp = lo->old_gfp_mask;
575
576         if (lo->lo_state != LLOOP_BOUND)
577                 return -ENXIO;
578
579         if (lo->lo_refcnt > count)        /* we needed one fd for the ioctl */
580                 return -EBUSY;
581
582         if (filp == NULL)
583                 return -EINVAL;
584
585         cfs_spin_lock_irq(&lo->lo_lock);
586         lo->lo_state = LLOOP_RUNDOWN;
587         cfs_spin_unlock_irq(&lo->lo_lock);
588         cfs_waitq_signal(&lo->lo_bh_wait);
589
590         cfs_down(&lo->lo_sem);
591         lo->lo_backing_file = NULL;
592         lo->ioctl = NULL;
593         lo->lo_device = NULL;
594         lo->lo_offset = 0;
595         lo->lo_sizelimit = 0;
596         lo->lo_flags = 0;
597         ll_invalidate_bdev(bdev, 0);
598         set_capacity(disks[lo->lo_number], 0);
599         bd_set_size(bdev, 0);
600         mapping_set_gfp_mask(filp->f_mapping, gfp);
601         lo->lo_state = LLOOP_UNBOUND;
602         fput(filp);
603         /* This is safe: open() is still holding a reference. */
604         cfs_module_put(THIS_MODULE);
605         return 0;
606 }
607
608 #ifdef HAVE_BLKDEV_PUT_2ARGS
609 static int lo_open(struct block_device *bdev, fmode_t mode)
610 {
611         struct lloop_device *lo = bdev->bd_disk->private_data;
612 #else
613 static int lo_open(struct inode *inode, struct file *file)
614 {
615         struct lloop_device *lo = inode->i_bdev->bd_disk->private_data;
616 #endif
617
618         cfs_mutex_lock(&lo->lo_ctl_mutex);
619         lo->lo_refcnt++;
620         cfs_mutex_unlock(&lo->lo_ctl_mutex);
621
622         return 0;
623 }
624
625 #ifdef HAVE_BLKDEV_PUT_2ARGS
626 static int lo_release(struct gendisk *disk, fmode_t mode)
627 {
628         struct lloop_device *lo = disk->private_data;
629 #else
630 static int lo_release(struct inode *inode, struct file *file)
631 {
632         struct lloop_device *lo = inode->i_bdev->bd_disk->private_data;
633 #endif
634
635         cfs_mutex_lock(&lo->lo_ctl_mutex);
636         --lo->lo_refcnt;
637         cfs_mutex_unlock(&lo->lo_ctl_mutex);
638
639         return 0;
640 }
641
642 /* lloop device node's ioctl function. */
643 #ifdef HAVE_BLKDEV_PUT_2ARGS
644 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
645                     unsigned int cmd, unsigned long arg)
646 {
647         struct lloop_device *lo = bdev->bd_disk->private_data;
648         struct inode *inode = NULL;
649         int err = 0;
650 #else
651 static int lo_ioctl(struct inode *inode, struct file *unused,
652                     unsigned int cmd, unsigned long arg)
653 {
654         struct lloop_device *lo = inode->i_bdev->bd_disk->private_data;
655         struct block_device *bdev = inode->i_bdev;
656         int err = 0;
657 #endif
658
659         cfs_mutex_lock(&lloop_mutex);
660         switch (cmd) {
661         case LL_IOC_LLOOP_DETACH: {
662                 err = loop_clr_fd(lo, bdev, 2);
663                 if (err == 0)
664                         ll_blkdev_put(bdev, 0); /* grabbed in LLOOP_ATTACH */
665                 break;
666         }
667
668         case LL_IOC_LLOOP_INFO: {
669                 struct lu_fid fid;
670
671                 LASSERT(lo->lo_backing_file != NULL);
672                 if (inode == NULL)
673                         inode = lo->lo_backing_file->f_dentry->d_inode;
674                 if (lo->lo_state == LLOOP_BOUND)
675                         fid = ll_i2info(inode)->lli_fid;
676                 else
677                         fid_zero(&fid);
678
679                 if (copy_to_user((struct lu_fid *)arg, &fid, sizeof(fid)))
680                         err = -EFAULT;
681                 break;
682         }
683
684         default:
685                 err = -EINVAL;
686                 break;
687         }
688         cfs_mutex_unlock(&lloop_mutex);
689
690         return err;
691 }
692
693 static struct block_device_operations lo_fops = {
694         .owner =        THIS_MODULE,
695         .open =         lo_open,
696         .release =      lo_release,
697         .ioctl =        lo_ioctl,
698 };
699
700 /* dynamic iocontrol callback.
701  * This callback is registered in lloop_init and will be called by
702  * ll_iocontrol_call.
703  *
704  * This is a llite regular file ioctl function. It takes the responsibility
705  * of attaching or detaching a file by a lloop's device numner.
706  */
707 static enum llioc_iter lloop_ioctl(struct inode *unused, struct file *file,
708                                    unsigned int cmd, unsigned long arg,
709                                    void *magic, int *rcp)
710 {
711         struct lloop_device *lo = NULL;
712         struct block_device *bdev = NULL;
713         int err = 0;
714         dev_t dev;
715
716         if (magic != ll_iocontrol_magic)
717                 return LLIOC_CONT;
718
719         if (disks == NULL)
720                 GOTO(out1, err = -ENODEV);
721
722         CWARN("Enter llop_ioctl\n");
723
724         cfs_mutex_lock(&lloop_mutex);
725         switch (cmd) {
726         case LL_IOC_LLOOP_ATTACH: {
727                 struct lloop_device *lo_free = NULL;
728                 int i;
729
730                 for (i = 0; i < max_loop; i++, lo = NULL) {
731                         lo = &loop_dev[i];
732                         if (lo->lo_state == LLOOP_UNBOUND) {
733                                 if (!lo_free)
734                                         lo_free = lo;
735                                 continue;
736                         }
737                         if (lo->lo_backing_file->f_dentry->d_inode ==
738                             file->f_dentry->d_inode)
739                                 break;
740                 }
741                 if (lo || !lo_free)
742                         GOTO(out, err = -EBUSY);
743
744                 lo = lo_free;
745                 dev = MKDEV(lloop_major, lo->lo_number);
746
747                 /* quit if the used pointer is writable */
748                 if (put_user((long)old_encode_dev(dev), (long*)arg))
749                         GOTO(out, err = -EFAULT);
750
751                 bdev = blkdev_get_by_dev(dev, file->f_mode, NULL);
752                 if (IS_ERR(bdev))
753                         GOTO(out, err = PTR_ERR(bdev));
754
755                 get_file(file);
756                 err = loop_set_fd(lo, NULL, bdev, file);
757                 if (err) {
758                         fput(file);
759                         ll_blkdev_put(bdev, 0);
760                 }
761
762                 break;
763         }
764
765         case LL_IOC_LLOOP_DETACH_BYDEV: {
766                 int minor;
767
768                 dev = old_decode_dev(arg);
769                 if (MAJOR(dev) != lloop_major)
770                         GOTO(out, err = -EINVAL);
771
772                 minor = MINOR(dev);
773                 if (minor > max_loop - 1)
774                         GOTO(out, err = -EINVAL);
775
776                 lo = &loop_dev[minor];
777                 if (lo->lo_state != LLOOP_BOUND)
778                         GOTO(out, err = -EINVAL);
779
780                 bdev = lo->lo_device;
781                 err = loop_clr_fd(lo, bdev, 1);
782                 if (err == 0)
783                         ll_blkdev_put(bdev, 0); /* grabbed in LLOOP_ATTACH */
784
785                 break;
786         }
787
788         default:
789                 err = -EINVAL;
790                 break;
791         }
792
793 out:
794         cfs_mutex_unlock(&lloop_mutex);
795 out1:
796         if (rcp)
797                 *rcp = err;
798         return LLIOC_STOP;
799 }
800
801 static int __init lloop_init(void)
802 {
803         int        i;
804         unsigned int cmdlist[] = {
805                 LL_IOC_LLOOP_ATTACH,
806                 LL_IOC_LLOOP_DETACH_BYDEV,
807         };
808
809         if (max_loop < 1 || max_loop > 256) {
810                 max_loop = MAX_LOOP_DEFAULT;
811                 CWARN("lloop: invalid max_loop (must be between"
812                       " 1 and 256), using default (%u)\n", max_loop);
813         }
814
815         lloop_major = register_blkdev(0, "lloop");
816         if (lloop_major < 0)
817                 return -EIO;
818
819         CDEBUG(D_CONFIG, "registered lloop major %d with %u minors\n",
820                lloop_major, max_loop);
821
822         ll_iocontrol_magic = ll_iocontrol_register(lloop_ioctl, 2, cmdlist);
823         if (ll_iocontrol_magic == NULL)
824                 goto out_mem1;
825
826         OBD_ALLOC_WAIT(loop_dev, max_loop * sizeof(*loop_dev));
827         if (!loop_dev)
828                 goto out_mem1;
829
830         OBD_ALLOC_WAIT(disks, max_loop * sizeof(*disks));
831         if (!disks)
832                 goto out_mem2;
833
834         for (i = 0; i < max_loop; i++) {
835                 disks[i] = alloc_disk(1);
836                 if (!disks[i])
837                         goto out_mem3;
838         }
839
840         cfs_mutex_init(&lloop_mutex);
841
842         for (i = 0; i < max_loop; i++) {
843                 struct lloop_device *lo = &loop_dev[i];
844                 struct gendisk *disk = disks[i];
845
846                 lo->lo_queue = blk_alloc_queue(GFP_KERNEL);
847                 if (!lo->lo_queue)
848                         goto out_mem4;
849
850                 cfs_mutex_init(&lo->lo_ctl_mutex);
851                 cfs_sema_init(&lo->lo_sem, 0);
852                 cfs_waitq_init(&lo->lo_bh_wait);
853                 lo->lo_number = i;
854                 cfs_spin_lock_init(&lo->lo_lock);
855                 disk->major = lloop_major;
856                 disk->first_minor = i;
857                 disk->fops = &lo_fops;
858                 sprintf(disk->disk_name, "lloop%d", i);
859                 disk->private_data = lo;
860                 disk->queue = lo->lo_queue;
861         }
862
863         /* We cannot fail after we call this, so another loop!*/
864         for (i = 0; i < max_loop; i++)
865                 add_disk(disks[i]);
866         return 0;
867
868 out_mem4:
869         while (i--)
870                 blk_cleanup_queue(loop_dev[i].lo_queue);
871         i = max_loop;
872 out_mem3:
873         while (i--)
874                 put_disk(disks[i]);
875         OBD_FREE(disks, max_loop * sizeof(*disks));
876 out_mem2:
877         OBD_FREE(loop_dev, max_loop * sizeof(*loop_dev));
878 out_mem1:
879         unregister_blkdev(lloop_major, "lloop");
880         ll_iocontrol_unregister(ll_iocontrol_magic);
881         CERROR("lloop: ran out of memory\n");
882         return -ENOMEM;
883 }
884
885 static void lloop_exit(void)
886 {
887         int i;
888
889         ll_iocontrol_unregister(ll_iocontrol_magic);
890         for (i = 0; i < max_loop; i++) {
891                 del_gendisk(disks[i]);
892                 blk_cleanup_queue(loop_dev[i].lo_queue);
893                 put_disk(disks[i]);
894         }
895         if (ll_unregister_blkdev(lloop_major, "lloop"))
896                 CWARN("lloop: cannot unregister blkdev\n");
897         else
898                 CDEBUG(D_CONFIG, "unregistered lloop major %d\n", lloop_major);
899
900         OBD_FREE(disks, max_loop * sizeof(*disks));
901         OBD_FREE(loop_dev, max_loop * sizeof(*loop_dev));
902 }
903
904 module_init(lloop_init);
905 module_exit(lloop_exit);
906
907 CFS_MODULE_PARM(max_loop, "i", int, 0444, "maximum of lloop_device");
908 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
909 MODULE_DESCRIPTION("Lustre virtual block device");
910 MODULE_LICENSE("GPL");