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