Whamcloud - gitweb
LU-8210 osd-ldiskfs: fix setting pages PageUptodate state
[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, 2014, Intel Corporation.
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 #include <linux/module.h>
83
84 #include <linux/sched.h>
85 #include <linux/kthread.h>
86 #include <linux/fs.h>
87 #include <linux/file.h>
88 #include <linux/stat.h>
89 #include <linux/errno.h>
90 #include <linux/major.h>
91 #include <linux/wait.h>
92 #include <linux/blkdev.h>
93 #include <linux/blkpg.h>
94 #include <linux/init.h>
95 #include <linux/swap.h>
96 #include <linux/slab.h>
97 #include <linux/suspend.h>
98 #include <linux/writeback.h>
99 #include <linux/buffer_head.h>                /* for invalidate_bdev() */
100 #include <linux/completion.h>
101 #include <linux/highmem.h>
102 #include <linux/gfp.h>
103 #include <linux/swap.h>
104 #include <linux/pagevec.h>
105
106 #include <asm/uaccess.h>
107
108 #include <lustre_lib.h>
109 #include "llite_internal.h"
110
111 #define LLOOP_MAX_SEGMENTS        LNET_MAX_IOV
112
113 /* Possible states of device */
114 enum {
115         LLOOP_UNBOUND,
116         LLOOP_BOUND,
117         LLOOP_RUNDOWN,
118 };
119
120 struct lloop_device {
121         int                  lo_number;
122         int                  lo_refcnt;
123         loff_t               lo_offset;
124         loff_t               lo_sizelimit;
125         int                  lo_flags;
126         struct file         *lo_backing_file;
127         struct block_device *lo_device;
128         unsigned             lo_blocksize;
129
130         gfp_t                   old_gfp_mask;
131
132         spinlock_t              lo_lock;
133         struct bio              *lo_bio;
134         struct bio              *lo_biotail;
135         int                     lo_state;
136         struct semaphore        lo_sem;
137         struct mutex            lo_ctl_mutex;
138         atomic_t                lo_pending;
139         wait_queue_head_t       lo_bh_wait;
140
141         struct request_queue *lo_queue;
142
143         const struct lu_env *lo_env;
144         struct cl_io         lo_io;
145         struct ll_dio_pages  lo_pvec;
146
147         /* data to handle bio for lustre. */
148         struct lo_request_data {
149                 struct page *lrd_pages[LLOOP_MAX_SEGMENTS];
150                 loff_t       lrd_offsets[LLOOP_MAX_SEGMENTS];
151         } lo_requests[1];
152 };
153
154 /*
155  * Loop flags
156  */
157 enum {
158         LO_FLAGS_READ_ONLY       = 1,
159 };
160
161 static int lloop_major;
162 #define MAX_LOOP_DEFAULT  16
163 static int max_loop = MAX_LOOP_DEFAULT;
164 static struct lloop_device *loop_dev;
165 static struct gendisk **disks;
166 static struct mutex lloop_mutex;
167 static void *ll_iocontrol_magic = NULL;
168
169 static loff_t get_loop_size(struct lloop_device *lo, struct file *file)
170 {
171         loff_t size, offset, loopsize;
172
173         /* Compute loopsize in bytes */
174         size = i_size_read(file->f_mapping->host);
175         offset = lo->lo_offset;
176         loopsize = size - offset;
177         if (lo->lo_sizelimit > 0 && lo->lo_sizelimit < loopsize)
178                 loopsize = lo->lo_sizelimit;
179
180         /*
181          * Unfortunately, if we want to do I/O on the device,
182          * the number of 512-byte sectors has to fit into a sector_t.
183          */
184         return loopsize >> 9;
185 }
186
187 static int do_bio_lustrebacked(struct lloop_device *lo, struct bio *head)
188 {
189         const struct lu_env  *env   = lo->lo_env;
190         struct cl_io         *io    = &lo->lo_io;
191         struct dentry        *de    = lo->lo_backing_file->f_path.dentry;
192         struct inode         *inode = de->d_inode;
193         struct cl_object     *obj = ll_i2info(inode)->lli_clob;
194         pgoff_t               offset;
195         int                   ret;
196 #ifdef HAVE_BVEC_ITER
197         struct bvec_iter      iter;
198         struct bio_vec        bvec;
199 #else
200         int                   iter;
201         struct bio_vec       *bvec;
202 #endif
203         int                   rw;
204         size_t                page_count = 0;
205         struct bio           *bio;
206         ssize_t               bytes;
207
208         struct ll_dio_pages  *pvec = &lo->lo_pvec;
209         struct page         **pages = pvec->ldp_pages;
210         loff_t               *offsets = pvec->ldp_offsets;
211
212         truncate_inode_pages(inode->i_mapping, 0);
213
214         /* initialize the IO */
215         memset(io, 0, sizeof(*io));
216         io->ci_obj = obj;
217         ret = cl_io_init(env, io, CIT_MISC, obj);
218         if (ret)
219                 return io->ci_result;
220         io->ci_lockreq = CILR_NEVER;
221
222         LASSERT(head != NULL);
223         rw = head->bi_rw;
224         for (bio = head; bio != NULL; bio = bio->bi_next) {
225                 LASSERT(rw == bio->bi_rw);
226
227 #ifdef HAVE_BVEC_ITER
228                 offset = (pgoff_t)(bio->bi_iter.bi_sector << 9) + lo->lo_offset;
229                 bio_for_each_segment_all(bvec, bio, iter) {
230                         BUG_ON(bvec.bv_offset != 0);
231                         BUG_ON(bvec.bv_len != PAGE_CACHE_SIZE);
232
233                         pages[page_count] = bvec.bv_page;
234                         offsets[page_count] = offset;
235                         page_count++;
236                         offset += bvec.bv_len;
237 #else
238                 offset = (pgoff_t)(bio->bi_sector << 9) + lo->lo_offset;
239                 bio_for_each_segment_all(bvec, bio, iter) {
240                         BUG_ON(bvec->bv_offset != 0);
241                         BUG_ON(bvec->bv_len != PAGE_CACHE_SIZE);
242
243                         pages[page_count] = bvec->bv_page;
244                         offsets[page_count] = offset;
245                         page_count++;
246                         offset += bvec->bv_len;
247 #endif
248                 }
249                 LASSERT(page_count <= LLOOP_MAX_SEGMENTS);
250         }
251
252         ll_stats_ops_tally(ll_i2sbi(inode),
253                         (rw == WRITE) ? LPROC_LL_BRW_WRITE : LPROC_LL_BRW_READ,
254                         page_count);
255
256         pvec->ldp_size = page_count << PAGE_CACHE_SHIFT;
257         pvec->ldp_nr = page_count;
258
259         /* FIXME: in ll_direct_rw_pages, it has to allocate many cl_page{}s to
260          * write those pages into OST. Even worse case is that more pages
261          * would be asked to write out to swap space, and then finally get here
262          * again.
263          * Unfortunately this is NOT easy to fix.
264          * Thoughts on solution:
265          * 0. Define a reserved pool for cl_pages, which could be a list of
266          *    pre-allocated cl_pages;
267          * 1. Define a new operation in cl_object_operations{}, says clo_depth,
268          *    which measures how many layers for this lustre object. Generally
269          *    speaking, the depth would be 2, one for llite, and one for lovsub.
270          *    However, for SNS, there will be more since we need additional page
271          *    to store parity;
272          * 2. Reserve the # of (page_count * depth) cl_pages from the reserved
273          *    pool. Afterwards, the clio would allocate the pages from reserved
274          *    pool, this guarantees we neeedn't allocate the cl_pages from
275          *    generic cl_page slab cache.
276          *    Of course, if there is NOT enough pages in the pool, we might
277          *    be asked to write less pages once, this purely depends on
278          *    implementation. Anyway, we should be careful to avoid deadlocking.
279          */
280         mutex_lock(&inode->i_mutex);
281         bytes = ll_direct_rw_pages(env, io, rw, inode, pvec);
282         mutex_unlock(&inode->i_mutex);
283         cl_io_fini(env, io);
284         return (bytes == pvec->ldp_size) ? 0 : (int)bytes;
285 }
286
287 /*
288  * Add bio to back of pending list
289  */
290 static void loop_add_bio(struct lloop_device *lo, struct bio *bio)
291 {
292         unsigned long flags;
293
294         spin_lock_irqsave(&lo->lo_lock, flags);
295         if (lo->lo_biotail) {
296                 lo->lo_biotail->bi_next = bio;
297                 lo->lo_biotail = bio;
298         } else
299                 lo->lo_bio = lo->lo_biotail = bio;
300         spin_unlock_irqrestore(&lo->lo_lock, flags);
301
302         atomic_inc(&lo->lo_pending);
303         if (waitqueue_active(&lo->lo_bh_wait))
304                 wake_up(&lo->lo_bh_wait);
305 }
306
307 /*
308  * Grab first pending buffer
309  */
310 static unsigned int loop_get_bio(struct lloop_device *lo, struct bio **req)
311 {
312         struct bio *first;
313         struct bio **bio;
314         unsigned int count = 0;
315         unsigned int page_count = 0;
316         int rw;
317
318         spin_lock_irq(&lo->lo_lock);
319         first = lo->lo_bio;
320         if (unlikely(first == NULL)) {
321                 spin_unlock_irq(&lo->lo_lock);
322                 return 0;
323         }
324
325         /* TODO: need to split the bio, too bad. */
326         LASSERT(first->bi_vcnt <= LLOOP_MAX_SEGMENTS);
327
328         rw = first->bi_rw;
329         bio = &lo->lo_bio;
330         while (*bio && (*bio)->bi_rw == rw) {
331 #ifdef HAVE_BVEC_ITER
332                 CDEBUG(D_INFO, "bio sector %llu size %u count %u vcnt%u \n",
333                        (unsigned long long)(*bio)->bi_iter.bi_sector,
334                        (*bio)->bi_iter.bi_size, page_count, (*bio)->bi_vcnt);
335 #else
336                 CDEBUG(D_INFO, "bio sector %llu size %u count %u vcnt%u \n",
337                        (unsigned long long)(*bio)->bi_sector, (*bio)->bi_size,
338                        page_count, (*bio)->bi_vcnt);
339 #endif
340                 if (page_count + (*bio)->bi_vcnt > LLOOP_MAX_SEGMENTS)
341                         break;
342
343                 page_count += (*bio)->bi_vcnt;
344                 count++;
345                 bio = &(*bio)->bi_next;
346         }
347         if (*bio) {
348                 /* Some of bios can't be mergable. */
349                 lo->lo_bio = *bio;
350                 *bio = NULL;
351         } else {
352                 /* Hit the end of queue */
353                 lo->lo_biotail = NULL;
354                 lo->lo_bio = NULL;
355         }
356         *req = first;
357         spin_unlock_irq(&lo->lo_lock);
358         return count;
359 }
360
361 static ll_mrf_ret
362 loop_make_request(struct request_queue *q, struct bio *old_bio)
363 {
364         struct lloop_device *lo = q->queuedata;
365         int rw = bio_rw(old_bio);
366         int inactive;
367
368         if (!lo)
369                 goto err;
370
371 #ifdef HAVE_BVEC_ITER
372         CDEBUG(D_INFO, "submit bio sector %llu size %u\n",
373                (unsigned long long)old_bio->bi_iter.bi_sector,
374                old_bio->bi_iter.bi_size);
375 #else
376         CDEBUG(D_INFO, "submit bio sector %llu size %u\n",
377                (unsigned long long)old_bio->bi_sector, old_bio->bi_size);
378 #endif
379
380         spin_lock_irq(&lo->lo_lock);
381         inactive = (lo->lo_state != LLOOP_BOUND);
382         spin_unlock_irq(&lo->lo_lock);
383         if (inactive)
384                 goto err;
385
386         if (rw == WRITE) {
387                 if (lo->lo_flags & LO_FLAGS_READ_ONLY)
388                         goto err;
389         } else if (rw == READA) {
390                 rw = READ;
391         } else if (rw != READ) {
392                 CERROR("lloop: unknown command (%x)\n", rw);
393                 goto err;
394         }
395         loop_add_bio(lo, old_bio);
396         LL_MRF_RETURN(0);
397 err:
398         bio_io_error(old_bio);
399         LL_MRF_RETURN(0);
400 }
401
402 #ifdef HAVE_REQUEST_QUEUE_UNPLUG_FN
403 /*
404  * kick off io on the underlying address space
405  */
406 static void loop_unplug(struct request_queue *q)
407 {
408         struct lloop_device *lo = q->queuedata;
409
410         clear_bit(QUEUE_FLAG_PLUGGED, &q->queue_flags);
411         blk_run_address_space(lo->lo_backing_file->f_mapping);
412 }
413 #endif
414
415 static inline void loop_handle_bio(struct lloop_device *lo, struct bio *bio)
416 {
417         int ret;
418
419         ret  = do_bio_lustrebacked(lo, bio);
420         while (bio) {
421                 struct bio *tmp = bio->bi_next;
422
423                 bio->bi_next = NULL;
424 #ifdef HAVE_BIO_ENDIO_USES_ONE_ARG
425                 bio->bi_error = ret;
426                 bio_endio(bio);
427 #else
428                 bio_endio(bio, ret);
429 #endif
430                 bio = tmp;
431         }
432 }
433
434 static inline int loop_active(struct lloop_device *lo)
435 {
436         return atomic_read(&lo->lo_pending) ||
437                (lo->lo_state == LLOOP_RUNDOWN);
438 }
439
440 /*
441  * worker thread that handles reads/writes to file backed loop devices,
442  * to avoid blocking in our make_request_fn.
443  */
444 static int loop_thread(void *data)
445 {
446         struct lloop_device *lo = data;
447         struct bio *bio;
448         unsigned int count;
449         unsigned long times = 0;
450         unsigned long total_count = 0;
451
452         struct lu_env *env;
453         __u16 refcheck;
454         int ret = 0;
455
456         set_user_nice(current, -20);
457
458         lo->lo_state = LLOOP_BOUND;
459
460         env = cl_env_get(&refcheck);
461         if (IS_ERR(env))
462                 GOTO(out, ret = PTR_ERR(env));
463
464         lo->lo_env = env;
465         memset(&lo->lo_pvec, 0, sizeof(lo->lo_pvec));
466         lo->lo_pvec.ldp_pages   = lo->lo_requests[0].lrd_pages;
467         lo->lo_pvec.ldp_offsets = lo->lo_requests[0].lrd_offsets;
468
469         /*
470          * up sem, we are running
471          */
472         up(&lo->lo_sem);
473
474         for (;;) {
475                 wait_event(lo->lo_bh_wait, loop_active(lo));
476                 if (!atomic_read(&lo->lo_pending)) {
477                         int exiting = 0;
478                         spin_lock_irq(&lo->lo_lock);
479                         exiting = (lo->lo_state == LLOOP_RUNDOWN);
480                         spin_unlock_irq(&lo->lo_lock);
481                         if (exiting)
482                                 break;
483                 }
484
485                 bio = NULL;
486                 count = loop_get_bio(lo, &bio);
487                 if (!count) {
488                         CWARN("lloop(minor: %d): missing bio\n", lo->lo_number);
489                         continue;
490                 }
491
492                 total_count += count;
493                 if (total_count < count) {     /* overflow */
494                         total_count = count;
495                         times = 1;
496                 } else {
497                         times++;
498                 }
499                 if ((times & 127) == 0) {
500                         CDEBUG(D_INFO, "total: %lu, count: %lu, avg: %lu\n",
501                                total_count, times, total_count / times);
502                 }
503
504                 LASSERT(bio != NULL);
505                 LASSERT(count <= atomic_read(&lo->lo_pending));
506                 loop_handle_bio(lo, bio);
507                 atomic_sub(count, &lo->lo_pending);
508         }
509         cl_env_put(env, &refcheck);
510
511 out:
512         up(&lo->lo_sem);
513         return ret;
514 }
515
516 static int loop_set_fd(struct lloop_device *lo, struct file *unused,
517                        struct block_device *bdev, struct file *file)
518 {
519         struct inode         *inode;
520         struct address_space *mapping;
521         int                   lo_flags = 0;
522         int                   error;
523         loff_t                size;
524
525         if (!try_module_get(THIS_MODULE))
526                 return -ENODEV;
527
528         error = -EBUSY;
529         if (lo->lo_state != LLOOP_UNBOUND)
530                 goto out;
531
532         mapping = file->f_mapping;
533         inode = mapping->host;
534
535         error = -EINVAL;
536         if (!S_ISREG(inode->i_mode) || inode->i_sb->s_magic != LL_SUPER_MAGIC)
537                 goto out;
538
539         if (!(file->f_mode & FMODE_WRITE))
540                 lo_flags |= LO_FLAGS_READ_ONLY;
541
542         size = get_loop_size(lo, file);
543
544         if ((loff_t)(sector_t)size != size) {
545                 error = -EFBIG;
546                 goto out;
547         }
548
549         /* remove all pages in cache so as dirty pages not to be existent. */
550         truncate_inode_pages(mapping, 0);
551
552         set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
553
554         lo->lo_blocksize = PAGE_CACHE_SIZE;
555         lo->lo_device = bdev;
556         lo->lo_flags = lo_flags;
557         lo->lo_backing_file = file;
558         lo->lo_sizelimit = 0;
559         lo->old_gfp_mask = mapping_gfp_mask(mapping);
560         mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
561
562         lo->lo_bio = lo->lo_biotail = NULL;
563
564         /*
565          * set queue make_request_fn, and add limits based on lower level
566          * device
567          */
568         blk_queue_make_request(lo->lo_queue, loop_make_request);
569         lo->lo_queue->queuedata = lo;
570 #ifdef HAVE_REQUEST_QUEUE_UNPLUG_FN
571         lo->lo_queue->unplug_fn = loop_unplug;
572 #endif
573
574         /* queue parameters */
575         blk_queue_max_hw_sectors(lo->lo_queue,
576                                  LLOOP_MAX_SEGMENTS << (PAGE_CACHE_SHIFT - 9));
577         blk_queue_max_segments(lo->lo_queue, LLOOP_MAX_SEGMENTS);
578
579         set_capacity(disks[lo->lo_number], size);
580         bd_set_size(bdev, size << 9);
581
582         set_blocksize(bdev, lo->lo_blocksize);
583
584         kthread_run(loop_thread, lo, "lloop%d", lo->lo_number);
585         down(&lo->lo_sem);
586         return 0;
587
588 out:
589         /* This is safe: open() is still holding a reference. */
590         module_put(THIS_MODULE);
591         return error;
592 }
593
594 static int loop_clr_fd(struct lloop_device *lo, struct block_device *bdev,
595                        int count)
596 {
597         struct file *filp = lo->lo_backing_file;
598         gfp_t gfp = lo->old_gfp_mask;
599
600         if (lo->lo_state != LLOOP_BOUND)
601                 return -ENXIO;
602
603         if (lo->lo_refcnt > count)        /* we needed one fd for the ioctl */
604                 return -EBUSY;
605
606         if (filp == NULL)
607                 return -EINVAL;
608
609         spin_lock_irq(&lo->lo_lock);
610         lo->lo_state = LLOOP_RUNDOWN;
611         spin_unlock_irq(&lo->lo_lock);
612         wake_up(&lo->lo_bh_wait);
613
614         down(&lo->lo_sem);
615         lo->lo_backing_file = NULL;
616         lo->lo_device = NULL;
617         lo->lo_offset = 0;
618         lo->lo_sizelimit = 0;
619         lo->lo_flags = 0;
620         invalidate_bdev(bdev);
621         set_capacity(disks[lo->lo_number], 0);
622         bd_set_size(bdev, 0);
623         mapping_set_gfp_mask(filp->f_mapping, gfp);
624         lo->lo_state = LLOOP_UNBOUND;
625         fput(filp);
626         /* This is safe: open() is still holding a reference. */
627         module_put(THIS_MODULE);
628         return 0;
629 }
630
631 static int lo_open(struct block_device *bdev, fmode_t mode)
632 {
633         struct lloop_device *lo = bdev->bd_disk->private_data;
634
635         mutex_lock(&lo->lo_ctl_mutex);
636         lo->lo_refcnt++;
637         mutex_unlock(&lo->lo_ctl_mutex);
638
639         return 0;
640 }
641
642 #ifdef HAVE_BLKDEV_RELEASE_RETURN_INT
643 static int
644 #else
645 static void
646 #endif
647 lo_release(struct gendisk *disk, fmode_t mode)
648 {
649         struct lloop_device *lo = disk->private_data;
650
651         mutex_lock(&lo->lo_ctl_mutex);
652         --lo->lo_refcnt;
653         mutex_unlock(&lo->lo_ctl_mutex);
654 #ifdef HAVE_BLKDEV_RELEASE_RETURN_INT
655         return 0;
656 #endif
657 }
658
659 /* lloop device node's ioctl function. */
660 static int lo_ioctl(struct block_device *bdev, fmode_t mode,
661                     unsigned int cmd, unsigned long arg)
662 {
663         struct lloop_device *lo = bdev->bd_disk->private_data;
664         int err = 0;
665
666         mutex_lock(&lloop_mutex);
667         switch (cmd) {
668         case LL_IOC_LLOOP_DETACH: {
669                 err = loop_clr_fd(lo, bdev, 2);
670                 if (err == 0)
671                         blkdev_put(bdev, 0); /* grabbed in LLOOP_ATTACH */
672                 break;
673         }
674
675         case LL_IOC_LLOOP_INFO: {
676                 struct inode *inode;
677                 struct lu_fid fid;
678
679                 if (lo->lo_backing_file == NULL) {
680                         err = -ENOENT;
681                         break;
682                 }
683                 inode = lo->lo_backing_file->f_path.dentry->d_inode;
684                 if (inode != NULL && lo->lo_state == LLOOP_BOUND)
685                         fid = ll_i2info(inode)->lli_fid;
686                 else
687                         fid_zero(&fid);
688
689                 if (copy_to_user((struct lu_fid __user *)arg,
690                                  &fid, sizeof(fid)))
691                         err = -EFAULT;
692                 break;
693         }
694
695         default:
696                 err = -EINVAL;
697                 break;
698         }
699         mutex_unlock(&lloop_mutex);
700
701         return err;
702 }
703
704 static struct block_device_operations lo_fops = {
705         .owner =        THIS_MODULE,
706         .open =         lo_open,
707         .release =      lo_release,
708         .ioctl =        lo_ioctl,
709 };
710
711 /* dynamic iocontrol callback.
712  * This callback is registered in lloop_init and will be called by
713  * ll_iocontrol_call.
714  *
715  * This is a llite regular file ioctl function. It takes the responsibility
716  * of attaching or detaching a file by a lloop's device numner.
717  */
718 static enum llioc_iter lloop_ioctl(struct inode *unused, struct file *file,
719                                    unsigned int cmd, unsigned long arg,
720                                    void *magic, int *rcp)
721 {
722         struct lloop_device *lo = NULL;
723         struct block_device *bdev = NULL;
724         int err = 0;
725         dev_t dev;
726
727         if (magic != ll_iocontrol_magic)
728                 return LLIOC_CONT;
729
730         if (disks == NULL)
731                 GOTO(out1, err = -ENODEV);
732
733         CWARN("Enter llop_ioctl\n");
734
735         mutex_lock(&lloop_mutex);
736         switch (cmd) {
737         case LL_IOC_LLOOP_ATTACH: {
738                 struct inode *inode = file->f_path.dentry->d_inode;
739                 struct lloop_device *lo_free = NULL;
740                 int i;
741
742                 for (i = 0; i < max_loop; i++, lo = NULL) {
743                         lo = &loop_dev[i];
744                         if (lo->lo_state == LLOOP_UNBOUND) {
745                                 if (!lo_free)
746                                         lo_free = lo;
747                                 continue;
748                         }
749                         if (lo->lo_backing_file->f_path.dentry->d_inode ==
750                             inode)
751                                 break;
752                 }
753                 if (lo || !lo_free)
754                         GOTO(out, err = -EBUSY);
755
756                 lo = lo_free;
757                 dev = MKDEV(lloop_major, lo->lo_number);
758
759                 /* quit if the used pointer is writable */
760                 if (put_user((long)old_encode_dev(dev), (long __user *)arg))
761                         GOTO(out, err = -EFAULT);
762
763                 bdev = blkdev_get_by_dev(dev, file->f_mode, NULL);
764                 if (IS_ERR(bdev))
765                         GOTO(out, err = PTR_ERR(bdev));
766
767                 get_file(file);
768                 err = loop_set_fd(lo, NULL, bdev, file);
769                 if (err) {
770                         fput(file);
771                         blkdev_put(bdev, 0);
772                 }
773
774                 break;
775         }
776
777         case LL_IOC_LLOOP_DETACH_BYDEV: {
778                 int minor;
779
780                 dev = old_decode_dev(arg);
781                 if (MAJOR(dev) != lloop_major)
782                         GOTO(out, err = -EINVAL);
783
784                 minor = MINOR(dev);
785                 if (minor > max_loop - 1)
786                         GOTO(out, err = -EINVAL);
787
788                 lo = &loop_dev[minor];
789                 if (lo->lo_state != LLOOP_BOUND)
790                         GOTO(out, err = -EINVAL);
791
792                 bdev = lo->lo_device;
793                 err = loop_clr_fd(lo, bdev, 1);
794                 if (err == 0)
795                         blkdev_put(bdev, 0); /* grabbed in LLOOP_ATTACH */
796
797                 break;
798         }
799
800         default:
801                 err = -EINVAL;
802                 break;
803         }
804
805 out:
806         mutex_unlock(&lloop_mutex);
807 out1:
808         if (rcp)
809                 *rcp = err;
810         return LLIOC_STOP;
811 }
812
813 static int __init lloop_init(void)
814 {
815         int        i;
816         unsigned int cmdlist[] = {
817                 LL_IOC_LLOOP_ATTACH,
818                 LL_IOC_LLOOP_DETACH_BYDEV,
819         };
820
821         if (max_loop < 1 || max_loop > 256) {
822                 max_loop = MAX_LOOP_DEFAULT;
823                 CWARN("lloop: invalid max_loop (must be between"
824                       " 1 and 256), using default (%u)\n", max_loop);
825         }
826
827         lloop_major = register_blkdev(0, "lloop");
828         if (lloop_major < 0)
829                 return -EIO;
830
831         CDEBUG(D_CONFIG, "registered lloop major %d with %u minors\n",
832                lloop_major, max_loop);
833
834         ll_iocontrol_magic = ll_iocontrol_register(lloop_ioctl, 2, cmdlist);
835         if (ll_iocontrol_magic == NULL)
836                 goto out_mem1;
837
838         OBD_ALLOC_WAIT(loop_dev, max_loop * sizeof(*loop_dev));
839         if (!loop_dev)
840                 goto out_mem1;
841
842         OBD_ALLOC_WAIT(disks, max_loop * sizeof(*disks));
843         if (!disks)
844                 goto out_mem2;
845
846         for (i = 0; i < max_loop; i++) {
847                 disks[i] = alloc_disk(1);
848                 if (!disks[i])
849                         goto out_mem3;
850         }
851
852         mutex_init(&lloop_mutex);
853
854         for (i = 0; i < max_loop; i++) {
855                 struct lloop_device *lo = &loop_dev[i];
856                 struct gendisk *disk = disks[i];
857
858                 lo->lo_queue = blk_alloc_queue(GFP_KERNEL);
859                 if (!lo->lo_queue)
860                         goto out_mem4;
861
862                 mutex_init(&lo->lo_ctl_mutex);
863                 sema_init(&lo->lo_sem, 0);
864                 init_waitqueue_head(&lo->lo_bh_wait);
865                 lo->lo_number = i;
866                 spin_lock_init(&lo->lo_lock);
867                 disk->major = lloop_major;
868                 disk->first_minor = i;
869                 disk->fops = &lo_fops;
870                 sprintf(disk->disk_name, "lloop%d", i);
871                 disk->private_data = lo;
872                 disk->queue = lo->lo_queue;
873         }
874
875         /* We cannot fail after we call this, so another loop!*/
876         for (i = 0; i < max_loop; i++)
877                 add_disk(disks[i]);
878         return 0;
879
880 out_mem4:
881         while (i--)
882                 blk_cleanup_queue(loop_dev[i].lo_queue);
883         i = max_loop;
884 out_mem3:
885         while (i--)
886                 put_disk(disks[i]);
887         OBD_FREE(disks, max_loop * sizeof(*disks));
888 out_mem2:
889         OBD_FREE(loop_dev, max_loop * sizeof(*loop_dev));
890 out_mem1:
891         unregister_blkdev(lloop_major, "lloop");
892         ll_iocontrol_unregister(ll_iocontrol_magic);
893         CERROR("lloop: ran out of memory\n");
894         return -ENOMEM;
895 }
896
897 static void __exit lloop_exit(void)
898 {
899         int i;
900
901         ll_iocontrol_unregister(ll_iocontrol_magic);
902         for (i = 0; i < max_loop; i++) {
903                 del_gendisk(disks[i]);
904                 blk_cleanup_queue(loop_dev[i].lo_queue);
905                 put_disk(disks[i]);
906         }
907         unregister_blkdev(lloop_major, "lloop");
908
909         OBD_FREE(disks, max_loop * sizeof(*disks));
910         OBD_FREE(loop_dev, max_loop * sizeof(*loop_dev));
911 }
912
913 module_param(max_loop, int, 0444);
914 MODULE_PARM_DESC(max_loop, "maximum of lloop_device");
915 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
916 MODULE_DESCRIPTION("Lustre virtual block device");
917 MODULE_VERSION(LUSTRE_VERSION_STRING);
918 MODULE_LICENSE("GPL");
919
920 module_init(lloop_init);
921 module_exit(lloop_exit);