Merge branch 'core/xen' into x86/urgent
[linux-2.6] / fs / xfs / linux-2.6 / xfs_buf.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include <linux/stddef.h>
20 #include <linux/errno.h>
21 #include <linux/slab.h>
22 #include <linux/pagemap.h>
23 #include <linux/init.h>
24 #include <linux/vmalloc.h>
25 #include <linux/bio.h>
26 #include <linux/sysctl.h>
27 #include <linux/proc_fs.h>
28 #include <linux/workqueue.h>
29 #include <linux/percpu.h>
30 #include <linux/blkdev.h>
31 #include <linux/hash.h>
32 #include <linux/kthread.h>
33 #include <linux/migrate.h>
34 #include <linux/backing-dev.h>
35 #include <linux/freezer.h>
36
37 static kmem_zone_t *xfs_buf_zone;
38 STATIC int xfsbufd(void *);
39 STATIC int xfsbufd_wakeup(int, gfp_t);
40 STATIC void xfs_buf_delwri_queue(xfs_buf_t *, int);
41 static struct shrinker xfs_buf_shake = {
42         .shrink = xfsbufd_wakeup,
43         .seeks = DEFAULT_SEEKS,
44 };
45
46 static struct workqueue_struct *xfslogd_workqueue;
47 struct workqueue_struct *xfsdatad_workqueue;
48
49 #ifdef XFS_BUF_TRACE
50 void
51 xfs_buf_trace(
52         xfs_buf_t       *bp,
53         char            *id,
54         void            *data,
55         void            *ra)
56 {
57         ktrace_enter(xfs_buf_trace_buf,
58                 bp, id,
59                 (void *)(unsigned long)bp->b_flags,
60                 (void *)(unsigned long)bp->b_hold.counter,
61                 (void *)(unsigned long)bp->b_sema.count,
62                 (void *)current,
63                 data, ra,
64                 (void *)(unsigned long)((bp->b_file_offset>>32) & 0xffffffff),
65                 (void *)(unsigned long)(bp->b_file_offset & 0xffffffff),
66                 (void *)(unsigned long)bp->b_buffer_length,
67                 NULL, NULL, NULL, NULL, NULL);
68 }
69 ktrace_t *xfs_buf_trace_buf;
70 #define XFS_BUF_TRACE_SIZE      4096
71 #define XB_TRACE(bp, id, data)  \
72         xfs_buf_trace(bp, id, (void *)data, (void *)__builtin_return_address(0))
73 #else
74 #define XB_TRACE(bp, id, data)  do { } while (0)
75 #endif
76
77 #ifdef XFS_BUF_LOCK_TRACKING
78 # define XB_SET_OWNER(bp)       ((bp)->b_last_holder = current->pid)
79 # define XB_CLEAR_OWNER(bp)     ((bp)->b_last_holder = -1)
80 # define XB_GET_OWNER(bp)       ((bp)->b_last_holder)
81 #else
82 # define XB_SET_OWNER(bp)       do { } while (0)
83 # define XB_CLEAR_OWNER(bp)     do { } while (0)
84 # define XB_GET_OWNER(bp)       do { } while (0)
85 #endif
86
87 #define xb_to_gfp(flags) \
88         ((((flags) & XBF_READ_AHEAD) ? __GFP_NORETRY : \
89           ((flags) & XBF_DONT_BLOCK) ? GFP_NOFS : GFP_KERNEL) | __GFP_NOWARN)
90
91 #define xb_to_km(flags) \
92          (((flags) & XBF_DONT_BLOCK) ? KM_NOFS : KM_SLEEP)
93
94 #define xfs_buf_allocate(flags) \
95         kmem_zone_alloc(xfs_buf_zone, xb_to_km(flags))
96 #define xfs_buf_deallocate(bp) \
97         kmem_zone_free(xfs_buf_zone, (bp));
98
99 /*
100  *      Page Region interfaces.
101  *
102  *      For pages in filesystems where the blocksize is smaller than the
103  *      pagesize, we use the page->private field (long) to hold a bitmap
104  *      of uptodate regions within the page.
105  *
106  *      Each such region is "bytes per page / bits per long" bytes long.
107  *
108  *      NBPPR == number-of-bytes-per-page-region
109  *      BTOPR == bytes-to-page-region (rounded up)
110  *      BTOPRT == bytes-to-page-region-truncated (rounded down)
111  */
112 #if (BITS_PER_LONG == 32)
113 #define PRSHIFT         (PAGE_CACHE_SHIFT - 5)  /* (32 == 1<<5) */
114 #elif (BITS_PER_LONG == 64)
115 #define PRSHIFT         (PAGE_CACHE_SHIFT - 6)  /* (64 == 1<<6) */
116 #else
117 #error BITS_PER_LONG must be 32 or 64
118 #endif
119 #define NBPPR           (PAGE_CACHE_SIZE/BITS_PER_LONG)
120 #define BTOPR(b)        (((unsigned int)(b) + (NBPPR - 1)) >> PRSHIFT)
121 #define BTOPRT(b)       (((unsigned int)(b) >> PRSHIFT))
122
123 STATIC unsigned long
124 page_region_mask(
125         size_t          offset,
126         size_t          length)
127 {
128         unsigned long   mask;
129         int             first, final;
130
131         first = BTOPR(offset);
132         final = BTOPRT(offset + length - 1);
133         first = min(first, final);
134
135         mask = ~0UL;
136         mask <<= BITS_PER_LONG - (final - first);
137         mask >>= BITS_PER_LONG - (final);
138
139         ASSERT(offset + length <= PAGE_CACHE_SIZE);
140         ASSERT((final - first) < BITS_PER_LONG && (final - first) >= 0);
141
142         return mask;
143 }
144
145 STATIC_INLINE void
146 set_page_region(
147         struct page     *page,
148         size_t          offset,
149         size_t          length)
150 {
151         set_page_private(page,
152                 page_private(page) | page_region_mask(offset, length));
153         if (page_private(page) == ~0UL)
154                 SetPageUptodate(page);
155 }
156
157 STATIC_INLINE int
158 test_page_region(
159         struct page     *page,
160         size_t          offset,
161         size_t          length)
162 {
163         unsigned long   mask = page_region_mask(offset, length);
164
165         return (mask && (page_private(page) & mask) == mask);
166 }
167
168 /*
169  *      Internal xfs_buf_t object manipulation
170  */
171
172 STATIC void
173 _xfs_buf_initialize(
174         xfs_buf_t               *bp,
175         xfs_buftarg_t           *target,
176         xfs_off_t               range_base,
177         size_t                  range_length,
178         xfs_buf_flags_t         flags)
179 {
180         /*
181          * We don't want certain flags to appear in b_flags.
182          */
183         flags &= ~(XBF_LOCK|XBF_MAPPED|XBF_DONT_BLOCK|XBF_READ_AHEAD);
184
185         memset(bp, 0, sizeof(xfs_buf_t));
186         atomic_set(&bp->b_hold, 1);
187         init_completion(&bp->b_iowait);
188         INIT_LIST_HEAD(&bp->b_list);
189         INIT_LIST_HEAD(&bp->b_hash_list);
190         init_MUTEX_LOCKED(&bp->b_sema); /* held, no waiters */
191         XB_SET_OWNER(bp);
192         bp->b_target = target;
193         bp->b_file_offset = range_base;
194         /*
195          * Set buffer_length and count_desired to the same value initially.
196          * I/O routines should use count_desired, which will be the same in
197          * most cases but may be reset (e.g. XFS recovery).
198          */
199         bp->b_buffer_length = bp->b_count_desired = range_length;
200         bp->b_flags = flags;
201         bp->b_bn = XFS_BUF_DADDR_NULL;
202         atomic_set(&bp->b_pin_count, 0);
203         init_waitqueue_head(&bp->b_waiters);
204
205         XFS_STATS_INC(xb_create);
206         XB_TRACE(bp, "initialize", target);
207 }
208
209 /*
210  *      Allocate a page array capable of holding a specified number
211  *      of pages, and point the page buf at it.
212  */
213 STATIC int
214 _xfs_buf_get_pages(
215         xfs_buf_t               *bp,
216         int                     page_count,
217         xfs_buf_flags_t         flags)
218 {
219         /* Make sure that we have a page list */
220         if (bp->b_pages == NULL) {
221                 bp->b_offset = xfs_buf_poff(bp->b_file_offset);
222                 bp->b_page_count = page_count;
223                 if (page_count <= XB_PAGES) {
224                         bp->b_pages = bp->b_page_array;
225                 } else {
226                         bp->b_pages = kmem_alloc(sizeof(struct page *) *
227                                         page_count, xb_to_km(flags));
228                         if (bp->b_pages == NULL)
229                                 return -ENOMEM;
230                 }
231                 memset(bp->b_pages, 0, sizeof(struct page *) * page_count);
232         }
233         return 0;
234 }
235
236 /*
237  *      Frees b_pages if it was allocated.
238  */
239 STATIC void
240 _xfs_buf_free_pages(
241         xfs_buf_t       *bp)
242 {
243         if (bp->b_pages != bp->b_page_array) {
244                 kmem_free(bp->b_pages);
245         }
246 }
247
248 /*
249  *      Releases the specified buffer.
250  *
251  *      The modification state of any associated pages is left unchanged.
252  *      The buffer most not be on any hash - use xfs_buf_rele instead for
253  *      hashed and refcounted buffers
254  */
255 void
256 xfs_buf_free(
257         xfs_buf_t               *bp)
258 {
259         XB_TRACE(bp, "free", 0);
260
261         ASSERT(list_empty(&bp->b_hash_list));
262
263         if (bp->b_flags & (_XBF_PAGE_CACHE|_XBF_PAGES)) {
264                 uint            i;
265
266                 if ((bp->b_flags & XBF_MAPPED) && (bp->b_page_count > 1))
267                        vm_unmap_ram(bp->b_addr - bp->b_offset, bp->b_page_count);
268
269                 for (i = 0; i < bp->b_page_count; i++) {
270                         struct page     *page = bp->b_pages[i];
271
272                         if (bp->b_flags & _XBF_PAGE_CACHE)
273                                 ASSERT(!PagePrivate(page));
274                         page_cache_release(page);
275                 }
276                 _xfs_buf_free_pages(bp);
277         }
278
279         xfs_buf_deallocate(bp);
280 }
281
282 /*
283  *      Finds all pages for buffer in question and builds it's page list.
284  */
285 STATIC int
286 _xfs_buf_lookup_pages(
287         xfs_buf_t               *bp,
288         uint                    flags)
289 {
290         struct address_space    *mapping = bp->b_target->bt_mapping;
291         size_t                  blocksize = bp->b_target->bt_bsize;
292         size_t                  size = bp->b_count_desired;
293         size_t                  nbytes, offset;
294         gfp_t                   gfp_mask = xb_to_gfp(flags);
295         unsigned short          page_count, i;
296         pgoff_t                 first;
297         xfs_off_t               end;
298         int                     error;
299
300         end = bp->b_file_offset + bp->b_buffer_length;
301         page_count = xfs_buf_btoc(end) - xfs_buf_btoct(bp->b_file_offset);
302
303         error = _xfs_buf_get_pages(bp, page_count, flags);
304         if (unlikely(error))
305                 return error;
306         bp->b_flags |= _XBF_PAGE_CACHE;
307
308         offset = bp->b_offset;
309         first = bp->b_file_offset >> PAGE_CACHE_SHIFT;
310
311         for (i = 0; i < bp->b_page_count; i++) {
312                 struct page     *page;
313                 uint            retries = 0;
314
315               retry:
316                 page = find_or_create_page(mapping, first + i, gfp_mask);
317                 if (unlikely(page == NULL)) {
318                         if (flags & XBF_READ_AHEAD) {
319                                 bp->b_page_count = i;
320                                 for (i = 0; i < bp->b_page_count; i++)
321                                         unlock_page(bp->b_pages[i]);
322                                 return -ENOMEM;
323                         }
324
325                         /*
326                          * This could deadlock.
327                          *
328                          * But until all the XFS lowlevel code is revamped to
329                          * handle buffer allocation failures we can't do much.
330                          */
331                         if (!(++retries % 100))
332                                 printk(KERN_ERR
333                                         "XFS: possible memory allocation "
334                                         "deadlock in %s (mode:0x%x)\n",
335                                         __func__, gfp_mask);
336
337                         XFS_STATS_INC(xb_page_retries);
338                         xfsbufd_wakeup(0, gfp_mask);
339                         congestion_wait(WRITE, HZ/50);
340                         goto retry;
341                 }
342
343                 XFS_STATS_INC(xb_page_found);
344
345                 nbytes = min_t(size_t, size, PAGE_CACHE_SIZE - offset);
346                 size -= nbytes;
347
348                 ASSERT(!PagePrivate(page));
349                 if (!PageUptodate(page)) {
350                         page_count--;
351                         if (blocksize >= PAGE_CACHE_SIZE) {
352                                 if (flags & XBF_READ)
353                                         bp->b_flags |= _XBF_PAGE_LOCKED;
354                         } else if (!PagePrivate(page)) {
355                                 if (test_page_region(page, offset, nbytes))
356                                         page_count++;
357                         }
358                 }
359
360                 bp->b_pages[i] = page;
361                 offset = 0;
362         }
363
364         if (!(bp->b_flags & _XBF_PAGE_LOCKED)) {
365                 for (i = 0; i < bp->b_page_count; i++)
366                         unlock_page(bp->b_pages[i]);
367         }
368
369         if (page_count == bp->b_page_count)
370                 bp->b_flags |= XBF_DONE;
371
372         XB_TRACE(bp, "lookup_pages", (long)page_count);
373         return error;
374 }
375
376 /*
377  *      Map buffer into kernel address-space if nessecary.
378  */
379 STATIC int
380 _xfs_buf_map_pages(
381         xfs_buf_t               *bp,
382         uint                    flags)
383 {
384         /* A single page buffer is always mappable */
385         if (bp->b_page_count == 1) {
386                 bp->b_addr = page_address(bp->b_pages[0]) + bp->b_offset;
387                 bp->b_flags |= XBF_MAPPED;
388         } else if (flags & XBF_MAPPED) {
389                bp->b_addr = vm_map_ram(bp->b_pages, bp->b_page_count,
390                                        -1, PAGE_KERNEL);
391                 if (unlikely(bp->b_addr == NULL))
392                         return -ENOMEM;
393                 bp->b_addr += bp->b_offset;
394                 bp->b_flags |= XBF_MAPPED;
395         }
396
397         return 0;
398 }
399
400 /*
401  *      Finding and Reading Buffers
402  */
403
404 /*
405  *      Look up, and creates if absent, a lockable buffer for
406  *      a given range of an inode.  The buffer is returned
407  *      locked.  If other overlapping buffers exist, they are
408  *      released before the new buffer is created and locked,
409  *      which may imply that this call will block until those buffers
410  *      are unlocked.  No I/O is implied by this call.
411  */
412 xfs_buf_t *
413 _xfs_buf_find(
414         xfs_buftarg_t           *btp,   /* block device target          */
415         xfs_off_t               ioff,   /* starting offset of range     */
416         size_t                  isize,  /* length of range              */
417         xfs_buf_flags_t         flags,
418         xfs_buf_t               *new_bp)
419 {
420         xfs_off_t               range_base;
421         size_t                  range_length;
422         xfs_bufhash_t           *hash;
423         xfs_buf_t               *bp, *n;
424
425         range_base = (ioff << BBSHIFT);
426         range_length = (isize << BBSHIFT);
427
428         /* Check for IOs smaller than the sector size / not sector aligned */
429         ASSERT(!(range_length < (1 << btp->bt_sshift)));
430         ASSERT(!(range_base & (xfs_off_t)btp->bt_smask));
431
432         hash = &btp->bt_hash[hash_long((unsigned long)ioff, btp->bt_hashshift)];
433
434         spin_lock(&hash->bh_lock);
435
436         list_for_each_entry_safe(bp, n, &hash->bh_list, b_hash_list) {
437                 ASSERT(btp == bp->b_target);
438                 if (bp->b_file_offset == range_base &&
439                     bp->b_buffer_length == range_length) {
440                         /*
441                          * If we look at something, bring it to the
442                          * front of the list for next time.
443                          */
444                         atomic_inc(&bp->b_hold);
445                         list_move(&bp->b_hash_list, &hash->bh_list);
446                         goto found;
447                 }
448         }
449
450         /* No match found */
451         if (new_bp) {
452                 _xfs_buf_initialize(new_bp, btp, range_base,
453                                 range_length, flags);
454                 new_bp->b_hash = hash;
455                 list_add(&new_bp->b_hash_list, &hash->bh_list);
456         } else {
457                 XFS_STATS_INC(xb_miss_locked);
458         }
459
460         spin_unlock(&hash->bh_lock);
461         return new_bp;
462
463 found:
464         spin_unlock(&hash->bh_lock);
465
466         /* Attempt to get the semaphore without sleeping,
467          * if this does not work then we need to drop the
468          * spinlock and do a hard attempt on the semaphore.
469          */
470         if (down_trylock(&bp->b_sema)) {
471                 if (!(flags & XBF_TRYLOCK)) {
472                         /* wait for buffer ownership */
473                         XB_TRACE(bp, "get_lock", 0);
474                         xfs_buf_lock(bp);
475                         XFS_STATS_INC(xb_get_locked_waited);
476                 } else {
477                         /* We asked for a trylock and failed, no need
478                          * to look at file offset and length here, we
479                          * know that this buffer at least overlaps our
480                          * buffer and is locked, therefore our buffer
481                          * either does not exist, or is this buffer.
482                          */
483                         xfs_buf_rele(bp);
484                         XFS_STATS_INC(xb_busy_locked);
485                         return NULL;
486                 }
487         } else {
488                 /* trylock worked */
489                 XB_SET_OWNER(bp);
490         }
491
492         if (bp->b_flags & XBF_STALE) {
493                 ASSERT((bp->b_flags & _XBF_DELWRI_Q) == 0);
494                 bp->b_flags &= XBF_MAPPED;
495         }
496         XB_TRACE(bp, "got_lock", 0);
497         XFS_STATS_INC(xb_get_locked);
498         return bp;
499 }
500
501 /*
502  *      Assembles a buffer covering the specified range.
503  *      Storage in memory for all portions of the buffer will be allocated,
504  *      although backing storage may not be.
505  */
506 xfs_buf_t *
507 xfs_buf_get_flags(
508         xfs_buftarg_t           *target,/* target for buffer            */
509         xfs_off_t               ioff,   /* starting offset of range     */
510         size_t                  isize,  /* length of range              */
511         xfs_buf_flags_t         flags)
512 {
513         xfs_buf_t               *bp, *new_bp;
514         int                     error = 0, i;
515
516         new_bp = xfs_buf_allocate(flags);
517         if (unlikely(!new_bp))
518                 return NULL;
519
520         bp = _xfs_buf_find(target, ioff, isize, flags, new_bp);
521         if (bp == new_bp) {
522                 error = _xfs_buf_lookup_pages(bp, flags);
523                 if (error)
524                         goto no_buffer;
525         } else {
526                 xfs_buf_deallocate(new_bp);
527                 if (unlikely(bp == NULL))
528                         return NULL;
529         }
530
531         for (i = 0; i < bp->b_page_count; i++)
532                 mark_page_accessed(bp->b_pages[i]);
533
534         if (!(bp->b_flags & XBF_MAPPED)) {
535                 error = _xfs_buf_map_pages(bp, flags);
536                 if (unlikely(error)) {
537                         printk(KERN_WARNING "%s: failed to map pages\n",
538                                         __func__);
539                         goto no_buffer;
540                 }
541         }
542
543         XFS_STATS_INC(xb_get);
544
545         /*
546          * Always fill in the block number now, the mapped cases can do
547          * their own overlay of this later.
548          */
549         bp->b_bn = ioff;
550         bp->b_count_desired = bp->b_buffer_length;
551
552         XB_TRACE(bp, "get", (unsigned long)flags);
553         return bp;
554
555  no_buffer:
556         if (flags & (XBF_LOCK | XBF_TRYLOCK))
557                 xfs_buf_unlock(bp);
558         xfs_buf_rele(bp);
559         return NULL;
560 }
561
562 STATIC int
563 _xfs_buf_read(
564         xfs_buf_t               *bp,
565         xfs_buf_flags_t         flags)
566 {
567         int                     status;
568
569         XB_TRACE(bp, "_xfs_buf_read", (unsigned long)flags);
570
571         ASSERT(!(flags & (XBF_DELWRI|XBF_WRITE)));
572         ASSERT(bp->b_bn != XFS_BUF_DADDR_NULL);
573
574         bp->b_flags &= ~(XBF_WRITE | XBF_ASYNC | XBF_DELWRI | \
575                         XBF_READ_AHEAD | _XBF_RUN_QUEUES);
576         bp->b_flags |= flags & (XBF_READ | XBF_ASYNC | \
577                         XBF_READ_AHEAD | _XBF_RUN_QUEUES);
578
579         status = xfs_buf_iorequest(bp);
580         if (!status && !(flags & XBF_ASYNC))
581                 status = xfs_buf_iowait(bp);
582         return status;
583 }
584
585 xfs_buf_t *
586 xfs_buf_read_flags(
587         xfs_buftarg_t           *target,
588         xfs_off_t               ioff,
589         size_t                  isize,
590         xfs_buf_flags_t         flags)
591 {
592         xfs_buf_t               *bp;
593
594         flags |= XBF_READ;
595
596         bp = xfs_buf_get_flags(target, ioff, isize, flags);
597         if (bp) {
598                 if (!XFS_BUF_ISDONE(bp)) {
599                         XB_TRACE(bp, "read", (unsigned long)flags);
600                         XFS_STATS_INC(xb_get_read);
601                         _xfs_buf_read(bp, flags);
602                 } else if (flags & XBF_ASYNC) {
603                         XB_TRACE(bp, "read_async", (unsigned long)flags);
604                         /*
605                          * Read ahead call which is already satisfied,
606                          * drop the buffer
607                          */
608                         goto no_buffer;
609                 } else {
610                         XB_TRACE(bp, "read_done", (unsigned long)flags);
611                         /* We do not want read in the flags */
612                         bp->b_flags &= ~XBF_READ;
613                 }
614         }
615
616         return bp;
617
618  no_buffer:
619         if (flags & (XBF_LOCK | XBF_TRYLOCK))
620                 xfs_buf_unlock(bp);
621         xfs_buf_rele(bp);
622         return NULL;
623 }
624
625 /*
626  *      If we are not low on memory then do the readahead in a deadlock
627  *      safe manner.
628  */
629 void
630 xfs_buf_readahead(
631         xfs_buftarg_t           *target,
632         xfs_off_t               ioff,
633         size_t                  isize,
634         xfs_buf_flags_t         flags)
635 {
636         struct backing_dev_info *bdi;
637
638         bdi = target->bt_mapping->backing_dev_info;
639         if (bdi_read_congested(bdi))
640                 return;
641
642         flags |= (XBF_TRYLOCK|XBF_ASYNC|XBF_READ_AHEAD);
643         xfs_buf_read_flags(target, ioff, isize, flags);
644 }
645
646 xfs_buf_t *
647 xfs_buf_get_empty(
648         size_t                  len,
649         xfs_buftarg_t           *target)
650 {
651         xfs_buf_t               *bp;
652
653         bp = xfs_buf_allocate(0);
654         if (bp)
655                 _xfs_buf_initialize(bp, target, 0, len, 0);
656         return bp;
657 }
658
659 static inline struct page *
660 mem_to_page(
661         void                    *addr)
662 {
663         if ((!is_vmalloc_addr(addr))) {
664                 return virt_to_page(addr);
665         } else {
666                 return vmalloc_to_page(addr);
667         }
668 }
669
670 int
671 xfs_buf_associate_memory(
672         xfs_buf_t               *bp,
673         void                    *mem,
674         size_t                  len)
675 {
676         int                     rval;
677         int                     i = 0;
678         unsigned long           pageaddr;
679         unsigned long           offset;
680         size_t                  buflen;
681         int                     page_count;
682
683         pageaddr = (unsigned long)mem & PAGE_CACHE_MASK;
684         offset = (unsigned long)mem - pageaddr;
685         buflen = PAGE_CACHE_ALIGN(len + offset);
686         page_count = buflen >> PAGE_CACHE_SHIFT;
687
688         /* Free any previous set of page pointers */
689         if (bp->b_pages)
690                 _xfs_buf_free_pages(bp);
691
692         bp->b_pages = NULL;
693         bp->b_addr = mem;
694
695         rval = _xfs_buf_get_pages(bp, page_count, 0);
696         if (rval)
697                 return rval;
698
699         bp->b_offset = offset;
700
701         for (i = 0; i < bp->b_page_count; i++) {
702                 bp->b_pages[i] = mem_to_page((void *)pageaddr);
703                 pageaddr += PAGE_CACHE_SIZE;
704         }
705
706         bp->b_count_desired = len;
707         bp->b_buffer_length = buflen;
708         bp->b_flags |= XBF_MAPPED;
709         bp->b_flags &= ~_XBF_PAGE_LOCKED;
710
711         return 0;
712 }
713
714 xfs_buf_t *
715 xfs_buf_get_noaddr(
716         size_t                  len,
717         xfs_buftarg_t           *target)
718 {
719         unsigned long           page_count = PAGE_ALIGN(len) >> PAGE_SHIFT;
720         int                     error, i;
721         xfs_buf_t               *bp;
722
723         bp = xfs_buf_allocate(0);
724         if (unlikely(bp == NULL))
725                 goto fail;
726         _xfs_buf_initialize(bp, target, 0, len, 0);
727
728         error = _xfs_buf_get_pages(bp, page_count, 0);
729         if (error)
730                 goto fail_free_buf;
731
732         for (i = 0; i < page_count; i++) {
733                 bp->b_pages[i] = alloc_page(GFP_KERNEL);
734                 if (!bp->b_pages[i])
735                         goto fail_free_mem;
736         }
737         bp->b_flags |= _XBF_PAGES;
738
739         error = _xfs_buf_map_pages(bp, XBF_MAPPED);
740         if (unlikely(error)) {
741                 printk(KERN_WARNING "%s: failed to map pages\n",
742                                 __func__);
743                 goto fail_free_mem;
744         }
745
746         xfs_buf_unlock(bp);
747
748         XB_TRACE(bp, "no_daddr", len);
749         return bp;
750
751  fail_free_mem:
752         while (--i >= 0)
753                 __free_page(bp->b_pages[i]);
754         _xfs_buf_free_pages(bp);
755  fail_free_buf:
756         xfs_buf_deallocate(bp);
757  fail:
758         return NULL;
759 }
760
761 /*
762  *      Increment reference count on buffer, to hold the buffer concurrently
763  *      with another thread which may release (free) the buffer asynchronously.
764  *      Must hold the buffer already to call this function.
765  */
766 void
767 xfs_buf_hold(
768         xfs_buf_t               *bp)
769 {
770         atomic_inc(&bp->b_hold);
771         XB_TRACE(bp, "hold", 0);
772 }
773
774 /*
775  *      Releases a hold on the specified buffer.  If the
776  *      the hold count is 1, calls xfs_buf_free.
777  */
778 void
779 xfs_buf_rele(
780         xfs_buf_t               *bp)
781 {
782         xfs_bufhash_t           *hash = bp->b_hash;
783
784         XB_TRACE(bp, "rele", bp->b_relse);
785
786         if (unlikely(!hash)) {
787                 ASSERT(!bp->b_relse);
788                 if (atomic_dec_and_test(&bp->b_hold))
789                         xfs_buf_free(bp);
790                 return;
791         }
792
793         ASSERT(atomic_read(&bp->b_hold) > 0);
794         if (atomic_dec_and_lock(&bp->b_hold, &hash->bh_lock)) {
795                 if (bp->b_relse) {
796                         atomic_inc(&bp->b_hold);
797                         spin_unlock(&hash->bh_lock);
798                         (*(bp->b_relse)) (bp);
799                 } else if (bp->b_flags & XBF_FS_MANAGED) {
800                         spin_unlock(&hash->bh_lock);
801                 } else {
802                         ASSERT(!(bp->b_flags & (XBF_DELWRI|_XBF_DELWRI_Q)));
803                         list_del_init(&bp->b_hash_list);
804                         spin_unlock(&hash->bh_lock);
805                         xfs_buf_free(bp);
806                 }
807         }
808 }
809
810
811 /*
812  *      Mutual exclusion on buffers.  Locking model:
813  *
814  *      Buffers associated with inodes for which buffer locking
815  *      is not enabled are not protected by semaphores, and are
816  *      assumed to be exclusively owned by the caller.  There is a
817  *      spinlock in the buffer, used by the caller when concurrent
818  *      access is possible.
819  */
820
821 /*
822  *      Locks a buffer object, if it is not already locked.
823  *      Note that this in no way locks the underlying pages, so it is only
824  *      useful for synchronizing concurrent use of buffer objects, not for
825  *      synchronizing independent access to the underlying pages.
826  */
827 int
828 xfs_buf_cond_lock(
829         xfs_buf_t               *bp)
830 {
831         int                     locked;
832
833         locked = down_trylock(&bp->b_sema) == 0;
834         if (locked) {
835                 XB_SET_OWNER(bp);
836         }
837         XB_TRACE(bp, "cond_lock", (long)locked);
838         return locked ? 0 : -EBUSY;
839 }
840
841 #if defined(DEBUG) || defined(XFS_BLI_TRACE)
842 int
843 xfs_buf_lock_value(
844         xfs_buf_t               *bp)
845 {
846         return bp->b_sema.count;
847 }
848 #endif
849
850 /*
851  *      Locks a buffer object.
852  *      Note that this in no way locks the underlying pages, so it is only
853  *      useful for synchronizing concurrent use of buffer objects, not for
854  *      synchronizing independent access to the underlying pages.
855  */
856 void
857 xfs_buf_lock(
858         xfs_buf_t               *bp)
859 {
860         XB_TRACE(bp, "lock", 0);
861         if (atomic_read(&bp->b_io_remaining))
862                 blk_run_address_space(bp->b_target->bt_mapping);
863         down(&bp->b_sema);
864         XB_SET_OWNER(bp);
865         XB_TRACE(bp, "locked", 0);
866 }
867
868 /*
869  *      Releases the lock on the buffer object.
870  *      If the buffer is marked delwri but is not queued, do so before we
871  *      unlock the buffer as we need to set flags correctly.  We also need to
872  *      take a reference for the delwri queue because the unlocker is going to
873  *      drop their's and they don't know we just queued it.
874  */
875 void
876 xfs_buf_unlock(
877         xfs_buf_t               *bp)
878 {
879         if ((bp->b_flags & (XBF_DELWRI|_XBF_DELWRI_Q)) == XBF_DELWRI) {
880                 atomic_inc(&bp->b_hold);
881                 bp->b_flags |= XBF_ASYNC;
882                 xfs_buf_delwri_queue(bp, 0);
883         }
884
885         XB_CLEAR_OWNER(bp);
886         up(&bp->b_sema);
887         XB_TRACE(bp, "unlock", 0);
888 }
889
890
891 /*
892  *      Pinning Buffer Storage in Memory
893  *      Ensure that no attempt to force a buffer to disk will succeed.
894  */
895 void
896 xfs_buf_pin(
897         xfs_buf_t               *bp)
898 {
899         atomic_inc(&bp->b_pin_count);
900         XB_TRACE(bp, "pin", (long)bp->b_pin_count.counter);
901 }
902
903 void
904 xfs_buf_unpin(
905         xfs_buf_t               *bp)
906 {
907         if (atomic_dec_and_test(&bp->b_pin_count))
908                 wake_up_all(&bp->b_waiters);
909         XB_TRACE(bp, "unpin", (long)bp->b_pin_count.counter);
910 }
911
912 int
913 xfs_buf_ispin(
914         xfs_buf_t               *bp)
915 {
916         return atomic_read(&bp->b_pin_count);
917 }
918
919 STATIC void
920 xfs_buf_wait_unpin(
921         xfs_buf_t               *bp)
922 {
923         DECLARE_WAITQUEUE       (wait, current);
924
925         if (atomic_read(&bp->b_pin_count) == 0)
926                 return;
927
928         add_wait_queue(&bp->b_waiters, &wait);
929         for (;;) {
930                 set_current_state(TASK_UNINTERRUPTIBLE);
931                 if (atomic_read(&bp->b_pin_count) == 0)
932                         break;
933                 if (atomic_read(&bp->b_io_remaining))
934                         blk_run_address_space(bp->b_target->bt_mapping);
935                 schedule();
936         }
937         remove_wait_queue(&bp->b_waiters, &wait);
938         set_current_state(TASK_RUNNING);
939 }
940
941 /*
942  *      Buffer Utility Routines
943  */
944
945 STATIC void
946 xfs_buf_iodone_work(
947         struct work_struct      *work)
948 {
949         xfs_buf_t               *bp =
950                 container_of(work, xfs_buf_t, b_iodone_work);
951
952         /*
953          * We can get an EOPNOTSUPP to ordered writes.  Here we clear the
954          * ordered flag and reissue them.  Because we can't tell the higher
955          * layers directly that they should not issue ordered I/O anymore, they
956          * need to check if the _XFS_BARRIER_FAILED flag was set during I/O completion.
957          */
958         if ((bp->b_error == EOPNOTSUPP) &&
959             (bp->b_flags & (XBF_ORDERED|XBF_ASYNC)) == (XBF_ORDERED|XBF_ASYNC)) {
960                 XB_TRACE(bp, "ordered_retry", bp->b_iodone);
961                 bp->b_flags &= ~XBF_ORDERED;
962                 bp->b_flags |= _XFS_BARRIER_FAILED;
963                 xfs_buf_iorequest(bp);
964         } else if (bp->b_iodone)
965                 (*(bp->b_iodone))(bp);
966         else if (bp->b_flags & XBF_ASYNC)
967                 xfs_buf_relse(bp);
968 }
969
970 void
971 xfs_buf_ioend(
972         xfs_buf_t               *bp,
973         int                     schedule)
974 {
975         bp->b_flags &= ~(XBF_READ | XBF_WRITE | XBF_READ_AHEAD);
976         if (bp->b_error == 0)
977                 bp->b_flags |= XBF_DONE;
978
979         XB_TRACE(bp, "iodone", bp->b_iodone);
980
981         if ((bp->b_iodone) || (bp->b_flags & XBF_ASYNC)) {
982                 if (schedule) {
983                         INIT_WORK(&bp->b_iodone_work, xfs_buf_iodone_work);
984                         queue_work(xfslogd_workqueue, &bp->b_iodone_work);
985                 } else {
986                         xfs_buf_iodone_work(&bp->b_iodone_work);
987                 }
988         } else {
989                 complete(&bp->b_iowait);
990         }
991 }
992
993 void
994 xfs_buf_ioerror(
995         xfs_buf_t               *bp,
996         int                     error)
997 {
998         ASSERT(error >= 0 && error <= 0xffff);
999         bp->b_error = (unsigned short)error;
1000         XB_TRACE(bp, "ioerror", (unsigned long)error);
1001 }
1002
1003 int
1004 xfs_bawrite(
1005         void                    *mp,
1006         struct xfs_buf          *bp)
1007 {
1008         XB_TRACE(bp, "bawrite", 0);
1009
1010         ASSERT(bp->b_bn != XFS_BUF_DADDR_NULL);
1011
1012         xfs_buf_delwri_dequeue(bp);
1013
1014         bp->b_flags &= ~(XBF_READ | XBF_DELWRI | XBF_READ_AHEAD);
1015         bp->b_flags |= (XBF_WRITE | XBF_ASYNC | _XBF_RUN_QUEUES);
1016
1017         bp->b_mount = mp;
1018         bp->b_strat = xfs_bdstrat_cb;
1019         return xfs_bdstrat_cb(bp);
1020 }
1021
1022 void
1023 xfs_bdwrite(
1024         void                    *mp,
1025         struct xfs_buf          *bp)
1026 {
1027         XB_TRACE(bp, "bdwrite", 0);
1028
1029         bp->b_strat = xfs_bdstrat_cb;
1030         bp->b_mount = mp;
1031
1032         bp->b_flags &= ~XBF_READ;
1033         bp->b_flags |= (XBF_DELWRI | XBF_ASYNC);
1034
1035         xfs_buf_delwri_queue(bp, 1);
1036 }
1037
1038 STATIC_INLINE void
1039 _xfs_buf_ioend(
1040         xfs_buf_t               *bp,
1041         int                     schedule)
1042 {
1043         if (atomic_dec_and_test(&bp->b_io_remaining) == 1) {
1044                 bp->b_flags &= ~_XBF_PAGE_LOCKED;
1045                 xfs_buf_ioend(bp, schedule);
1046         }
1047 }
1048
1049 STATIC void
1050 xfs_buf_bio_end_io(
1051         struct bio              *bio,
1052         int                     error)
1053 {
1054         xfs_buf_t               *bp = (xfs_buf_t *)bio->bi_private;
1055         unsigned int            blocksize = bp->b_target->bt_bsize;
1056         struct bio_vec          *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
1057
1058         xfs_buf_ioerror(bp, -error);
1059
1060         do {
1061                 struct page     *page = bvec->bv_page;
1062
1063                 ASSERT(!PagePrivate(page));
1064                 if (unlikely(bp->b_error)) {
1065                         if (bp->b_flags & XBF_READ)
1066                                 ClearPageUptodate(page);
1067                 } else if (blocksize >= PAGE_CACHE_SIZE) {
1068                         SetPageUptodate(page);
1069                 } else if (!PagePrivate(page) &&
1070                                 (bp->b_flags & _XBF_PAGE_CACHE)) {
1071                         set_page_region(page, bvec->bv_offset, bvec->bv_len);
1072                 }
1073
1074                 if (--bvec >= bio->bi_io_vec)
1075                         prefetchw(&bvec->bv_page->flags);
1076
1077                 if (bp->b_flags & _XBF_PAGE_LOCKED)
1078                         unlock_page(page);
1079         } while (bvec >= bio->bi_io_vec);
1080
1081         _xfs_buf_ioend(bp, 1);
1082         bio_put(bio);
1083 }
1084
1085 STATIC void
1086 _xfs_buf_ioapply(
1087         xfs_buf_t               *bp)
1088 {
1089         int                     rw, map_i, total_nr_pages, nr_pages;
1090         struct bio              *bio;
1091         int                     offset = bp->b_offset;
1092         int                     size = bp->b_count_desired;
1093         sector_t                sector = bp->b_bn;
1094         unsigned int            blocksize = bp->b_target->bt_bsize;
1095
1096         total_nr_pages = bp->b_page_count;
1097         map_i = 0;
1098
1099         if (bp->b_flags & XBF_ORDERED) {
1100                 ASSERT(!(bp->b_flags & XBF_READ));
1101                 rw = WRITE_BARRIER;
1102         } else if (bp->b_flags & _XBF_RUN_QUEUES) {
1103                 ASSERT(!(bp->b_flags & XBF_READ_AHEAD));
1104                 bp->b_flags &= ~_XBF_RUN_QUEUES;
1105                 rw = (bp->b_flags & XBF_WRITE) ? WRITE_SYNC : READ_SYNC;
1106         } else {
1107                 rw = (bp->b_flags & XBF_WRITE) ? WRITE :
1108                      (bp->b_flags & XBF_READ_AHEAD) ? READA : READ;
1109         }
1110
1111         /* Special code path for reading a sub page size buffer in --
1112          * we populate up the whole page, and hence the other metadata
1113          * in the same page.  This optimization is only valid when the
1114          * filesystem block size is not smaller than the page size.
1115          */
1116         if ((bp->b_buffer_length < PAGE_CACHE_SIZE) &&
1117             ((bp->b_flags & (XBF_READ|_XBF_PAGE_LOCKED)) ==
1118               (XBF_READ|_XBF_PAGE_LOCKED)) &&
1119             (blocksize >= PAGE_CACHE_SIZE)) {
1120                 bio = bio_alloc(GFP_NOIO, 1);
1121
1122                 bio->bi_bdev = bp->b_target->bt_bdev;
1123                 bio->bi_sector = sector - (offset >> BBSHIFT);
1124                 bio->bi_end_io = xfs_buf_bio_end_io;
1125                 bio->bi_private = bp;
1126
1127                 bio_add_page(bio, bp->b_pages[0], PAGE_CACHE_SIZE, 0);
1128                 size = 0;
1129
1130                 atomic_inc(&bp->b_io_remaining);
1131
1132                 goto submit_io;
1133         }
1134
1135 next_chunk:
1136         atomic_inc(&bp->b_io_remaining);
1137         nr_pages = BIO_MAX_SECTORS >> (PAGE_SHIFT - BBSHIFT);
1138         if (nr_pages > total_nr_pages)
1139                 nr_pages = total_nr_pages;
1140
1141         bio = bio_alloc(GFP_NOIO, nr_pages);
1142         bio->bi_bdev = bp->b_target->bt_bdev;
1143         bio->bi_sector = sector;
1144         bio->bi_end_io = xfs_buf_bio_end_io;
1145         bio->bi_private = bp;
1146
1147         for (; size && nr_pages; nr_pages--, map_i++) {
1148                 int     rbytes, nbytes = PAGE_CACHE_SIZE - offset;
1149
1150                 if (nbytes > size)
1151                         nbytes = size;
1152
1153                 rbytes = bio_add_page(bio, bp->b_pages[map_i], nbytes, offset);
1154                 if (rbytes < nbytes)
1155                         break;
1156
1157                 offset = 0;
1158                 sector += nbytes >> BBSHIFT;
1159                 size -= nbytes;
1160                 total_nr_pages--;
1161         }
1162
1163 submit_io:
1164         if (likely(bio->bi_size)) {
1165                 submit_bio(rw, bio);
1166                 if (size)
1167                         goto next_chunk;
1168         } else {
1169                 bio_put(bio);
1170                 xfs_buf_ioerror(bp, EIO);
1171         }
1172 }
1173
1174 int
1175 xfs_buf_iorequest(
1176         xfs_buf_t               *bp)
1177 {
1178         XB_TRACE(bp, "iorequest", 0);
1179
1180         if (bp->b_flags & XBF_DELWRI) {
1181                 xfs_buf_delwri_queue(bp, 1);
1182                 return 0;
1183         }
1184
1185         if (bp->b_flags & XBF_WRITE) {
1186                 xfs_buf_wait_unpin(bp);
1187         }
1188
1189         xfs_buf_hold(bp);
1190
1191         /* Set the count to 1 initially, this will stop an I/O
1192          * completion callout which happens before we have started
1193          * all the I/O from calling xfs_buf_ioend too early.
1194          */
1195         atomic_set(&bp->b_io_remaining, 1);
1196         _xfs_buf_ioapply(bp);
1197         _xfs_buf_ioend(bp, 0);
1198
1199         xfs_buf_rele(bp);
1200         return 0;
1201 }
1202
1203 /*
1204  *      Waits for I/O to complete on the buffer supplied.
1205  *      It returns immediately if no I/O is pending.
1206  *      It returns the I/O error code, if any, or 0 if there was no error.
1207  */
1208 int
1209 xfs_buf_iowait(
1210         xfs_buf_t               *bp)
1211 {
1212         XB_TRACE(bp, "iowait", 0);
1213         if (atomic_read(&bp->b_io_remaining))
1214                 blk_run_address_space(bp->b_target->bt_mapping);
1215         wait_for_completion(&bp->b_iowait);
1216         XB_TRACE(bp, "iowaited", (long)bp->b_error);
1217         return bp->b_error;
1218 }
1219
1220 xfs_caddr_t
1221 xfs_buf_offset(
1222         xfs_buf_t               *bp,
1223         size_t                  offset)
1224 {
1225         struct page             *page;
1226
1227         if (bp->b_flags & XBF_MAPPED)
1228                 return XFS_BUF_PTR(bp) + offset;
1229
1230         offset += bp->b_offset;
1231         page = bp->b_pages[offset >> PAGE_CACHE_SHIFT];
1232         return (xfs_caddr_t)page_address(page) + (offset & (PAGE_CACHE_SIZE-1));
1233 }
1234
1235 /*
1236  *      Move data into or out of a buffer.
1237  */
1238 void
1239 xfs_buf_iomove(
1240         xfs_buf_t               *bp,    /* buffer to process            */
1241         size_t                  boff,   /* starting buffer offset       */
1242         size_t                  bsize,  /* length to copy               */
1243         caddr_t                 data,   /* data address                 */
1244         xfs_buf_rw_t            mode)   /* read/write/zero flag         */
1245 {
1246         size_t                  bend, cpoff, csize;
1247         struct page             *page;
1248
1249         bend = boff + bsize;
1250         while (boff < bend) {
1251                 page = bp->b_pages[xfs_buf_btoct(boff + bp->b_offset)];
1252                 cpoff = xfs_buf_poff(boff + bp->b_offset);
1253                 csize = min_t(size_t,
1254                               PAGE_CACHE_SIZE-cpoff, bp->b_count_desired-boff);
1255
1256                 ASSERT(((csize + cpoff) <= PAGE_CACHE_SIZE));
1257
1258                 switch (mode) {
1259                 case XBRW_ZERO:
1260                         memset(page_address(page) + cpoff, 0, csize);
1261                         break;
1262                 case XBRW_READ:
1263                         memcpy(data, page_address(page) + cpoff, csize);
1264                         break;
1265                 case XBRW_WRITE:
1266                         memcpy(page_address(page) + cpoff, data, csize);
1267                 }
1268
1269                 boff += csize;
1270                 data += csize;
1271         }
1272 }
1273
1274 /*
1275  *      Handling of buffer targets (buftargs).
1276  */
1277
1278 /*
1279  *      Wait for any bufs with callbacks that have been submitted but
1280  *      have not yet returned... walk the hash list for the target.
1281  */
1282 void
1283 xfs_wait_buftarg(
1284         xfs_buftarg_t   *btp)
1285 {
1286         xfs_buf_t       *bp, *n;
1287         xfs_bufhash_t   *hash;
1288         uint            i;
1289
1290         for (i = 0; i < (1 << btp->bt_hashshift); i++) {
1291                 hash = &btp->bt_hash[i];
1292 again:
1293                 spin_lock(&hash->bh_lock);
1294                 list_for_each_entry_safe(bp, n, &hash->bh_list, b_hash_list) {
1295                         ASSERT(btp == bp->b_target);
1296                         if (!(bp->b_flags & XBF_FS_MANAGED)) {
1297                                 spin_unlock(&hash->bh_lock);
1298                                 /*
1299                                  * Catch superblock reference count leaks
1300                                  * immediately
1301                                  */
1302                                 BUG_ON(bp->b_bn == 0);
1303                                 delay(100);
1304                                 goto again;
1305                         }
1306                 }
1307                 spin_unlock(&hash->bh_lock);
1308         }
1309 }
1310
1311 /*
1312  *      Allocate buffer hash table for a given target.
1313  *      For devices containing metadata (i.e. not the log/realtime devices)
1314  *      we need to allocate a much larger hash table.
1315  */
1316 STATIC void
1317 xfs_alloc_bufhash(
1318         xfs_buftarg_t           *btp,
1319         int                     external)
1320 {
1321         unsigned int            i;
1322
1323         btp->bt_hashshift = external ? 3 : 8;   /* 8 or 256 buckets */
1324         btp->bt_hashmask = (1 << btp->bt_hashshift) - 1;
1325         btp->bt_hash = kmem_zalloc((1 << btp->bt_hashshift) *
1326                                         sizeof(xfs_bufhash_t), KM_SLEEP | KM_LARGE);
1327         for (i = 0; i < (1 << btp->bt_hashshift); i++) {
1328                 spin_lock_init(&btp->bt_hash[i].bh_lock);
1329                 INIT_LIST_HEAD(&btp->bt_hash[i].bh_list);
1330         }
1331 }
1332
1333 STATIC void
1334 xfs_free_bufhash(
1335         xfs_buftarg_t           *btp)
1336 {
1337         kmem_free(btp->bt_hash);
1338         btp->bt_hash = NULL;
1339 }
1340
1341 /*
1342  *      buftarg list for delwrite queue processing
1343  */
1344 static LIST_HEAD(xfs_buftarg_list);
1345 static DEFINE_SPINLOCK(xfs_buftarg_lock);
1346
1347 STATIC void
1348 xfs_register_buftarg(
1349         xfs_buftarg_t           *btp)
1350 {
1351         spin_lock(&xfs_buftarg_lock);
1352         list_add(&btp->bt_list, &xfs_buftarg_list);
1353         spin_unlock(&xfs_buftarg_lock);
1354 }
1355
1356 STATIC void
1357 xfs_unregister_buftarg(
1358         xfs_buftarg_t           *btp)
1359 {
1360         spin_lock(&xfs_buftarg_lock);
1361         list_del(&btp->bt_list);
1362         spin_unlock(&xfs_buftarg_lock);
1363 }
1364
1365 void
1366 xfs_free_buftarg(
1367         xfs_buftarg_t           *btp)
1368 {
1369         xfs_flush_buftarg(btp, 1);
1370         xfs_blkdev_issue_flush(btp);
1371         xfs_free_bufhash(btp);
1372         iput(btp->bt_mapping->host);
1373
1374         /* Unregister the buftarg first so that we don't get a
1375          * wakeup finding a non-existent task
1376          */
1377         xfs_unregister_buftarg(btp);
1378         kthread_stop(btp->bt_task);
1379
1380         kmem_free(btp);
1381 }
1382
1383 STATIC int
1384 xfs_setsize_buftarg_flags(
1385         xfs_buftarg_t           *btp,
1386         unsigned int            blocksize,
1387         unsigned int            sectorsize,
1388         int                     verbose)
1389 {
1390         btp->bt_bsize = blocksize;
1391         btp->bt_sshift = ffs(sectorsize) - 1;
1392         btp->bt_smask = sectorsize - 1;
1393
1394         if (set_blocksize(btp->bt_bdev, sectorsize)) {
1395                 printk(KERN_WARNING
1396                         "XFS: Cannot set_blocksize to %u on device %s\n",
1397                         sectorsize, XFS_BUFTARG_NAME(btp));
1398                 return EINVAL;
1399         }
1400
1401         if (verbose &&
1402             (PAGE_CACHE_SIZE / BITS_PER_LONG) > sectorsize) {
1403                 printk(KERN_WARNING
1404                         "XFS: %u byte sectors in use on device %s.  "
1405                         "This is suboptimal; %u or greater is ideal.\n",
1406                         sectorsize, XFS_BUFTARG_NAME(btp),
1407                         (unsigned int)PAGE_CACHE_SIZE / BITS_PER_LONG);
1408         }
1409
1410         return 0;
1411 }
1412
1413 /*
1414  *      When allocating the initial buffer target we have not yet
1415  *      read in the superblock, so don't know what sized sectors
1416  *      are being used is at this early stage.  Play safe.
1417  */
1418 STATIC int
1419 xfs_setsize_buftarg_early(
1420         xfs_buftarg_t           *btp,
1421         struct block_device     *bdev)
1422 {
1423         return xfs_setsize_buftarg_flags(btp,
1424                         PAGE_CACHE_SIZE, bdev_hardsect_size(bdev), 0);
1425 }
1426
1427 int
1428 xfs_setsize_buftarg(
1429         xfs_buftarg_t           *btp,
1430         unsigned int            blocksize,
1431         unsigned int            sectorsize)
1432 {
1433         return xfs_setsize_buftarg_flags(btp, blocksize, sectorsize, 1);
1434 }
1435
1436 STATIC int
1437 xfs_mapping_buftarg(
1438         xfs_buftarg_t           *btp,
1439         struct block_device     *bdev)
1440 {
1441         struct backing_dev_info *bdi;
1442         struct inode            *inode;
1443         struct address_space    *mapping;
1444         static const struct address_space_operations mapping_aops = {
1445                 .sync_page = block_sync_page,
1446                 .migratepage = fail_migrate_page,
1447         };
1448
1449         inode = new_inode(bdev->bd_inode->i_sb);
1450         if (!inode) {
1451                 printk(KERN_WARNING
1452                         "XFS: Cannot allocate mapping inode for device %s\n",
1453                         XFS_BUFTARG_NAME(btp));
1454                 return ENOMEM;
1455         }
1456         inode->i_mode = S_IFBLK;
1457         inode->i_bdev = bdev;
1458         inode->i_rdev = bdev->bd_dev;
1459         bdi = blk_get_backing_dev_info(bdev);
1460         if (!bdi)
1461                 bdi = &default_backing_dev_info;
1462         mapping = &inode->i_data;
1463         mapping->a_ops = &mapping_aops;
1464         mapping->backing_dev_info = bdi;
1465         mapping_set_gfp_mask(mapping, GFP_NOFS);
1466         btp->bt_mapping = mapping;
1467         return 0;
1468 }
1469
1470 STATIC int
1471 xfs_alloc_delwrite_queue(
1472         xfs_buftarg_t           *btp)
1473 {
1474         int     error = 0;
1475
1476         INIT_LIST_HEAD(&btp->bt_list);
1477         INIT_LIST_HEAD(&btp->bt_delwrite_queue);
1478         spin_lock_init(&btp->bt_delwrite_lock);
1479         btp->bt_flags = 0;
1480         btp->bt_task = kthread_run(xfsbufd, btp, "xfsbufd");
1481         if (IS_ERR(btp->bt_task)) {
1482                 error = PTR_ERR(btp->bt_task);
1483                 goto out_error;
1484         }
1485         xfs_register_buftarg(btp);
1486 out_error:
1487         return error;
1488 }
1489
1490 xfs_buftarg_t *
1491 xfs_alloc_buftarg(
1492         struct block_device     *bdev,
1493         int                     external)
1494 {
1495         xfs_buftarg_t           *btp;
1496
1497         btp = kmem_zalloc(sizeof(*btp), KM_SLEEP);
1498
1499         btp->bt_dev =  bdev->bd_dev;
1500         btp->bt_bdev = bdev;
1501         if (xfs_setsize_buftarg_early(btp, bdev))
1502                 goto error;
1503         if (xfs_mapping_buftarg(btp, bdev))
1504                 goto error;
1505         if (xfs_alloc_delwrite_queue(btp))
1506                 goto error;
1507         xfs_alloc_bufhash(btp, external);
1508         return btp;
1509
1510 error:
1511         kmem_free(btp);
1512         return NULL;
1513 }
1514
1515
1516 /*
1517  *      Delayed write buffer handling
1518  */
1519 STATIC void
1520 xfs_buf_delwri_queue(
1521         xfs_buf_t               *bp,
1522         int                     unlock)
1523 {
1524         struct list_head        *dwq = &bp->b_target->bt_delwrite_queue;
1525         spinlock_t              *dwlk = &bp->b_target->bt_delwrite_lock;
1526
1527         XB_TRACE(bp, "delwri_q", (long)unlock);
1528         ASSERT((bp->b_flags&(XBF_DELWRI|XBF_ASYNC)) == (XBF_DELWRI|XBF_ASYNC));
1529
1530         spin_lock(dwlk);
1531         /* If already in the queue, dequeue and place at tail */
1532         if (!list_empty(&bp->b_list)) {
1533                 ASSERT(bp->b_flags & _XBF_DELWRI_Q);
1534                 if (unlock)
1535                         atomic_dec(&bp->b_hold);
1536                 list_del(&bp->b_list);
1537         }
1538
1539         bp->b_flags |= _XBF_DELWRI_Q;
1540         list_add_tail(&bp->b_list, dwq);
1541         bp->b_queuetime = jiffies;
1542         spin_unlock(dwlk);
1543
1544         if (unlock)
1545                 xfs_buf_unlock(bp);
1546 }
1547
1548 void
1549 xfs_buf_delwri_dequeue(
1550         xfs_buf_t               *bp)
1551 {
1552         spinlock_t              *dwlk = &bp->b_target->bt_delwrite_lock;
1553         int                     dequeued = 0;
1554
1555         spin_lock(dwlk);
1556         if ((bp->b_flags & XBF_DELWRI) && !list_empty(&bp->b_list)) {
1557                 ASSERT(bp->b_flags & _XBF_DELWRI_Q);
1558                 list_del_init(&bp->b_list);
1559                 dequeued = 1;
1560         }
1561         bp->b_flags &= ~(XBF_DELWRI|_XBF_DELWRI_Q);
1562         spin_unlock(dwlk);
1563
1564         if (dequeued)
1565                 xfs_buf_rele(bp);
1566
1567         XB_TRACE(bp, "delwri_dq", (long)dequeued);
1568 }
1569
1570 STATIC void
1571 xfs_buf_runall_queues(
1572         struct workqueue_struct *queue)
1573 {
1574         flush_workqueue(queue);
1575 }
1576
1577 STATIC int
1578 xfsbufd_wakeup(
1579         int                     priority,
1580         gfp_t                   mask)
1581 {
1582         xfs_buftarg_t           *btp;
1583
1584         spin_lock(&xfs_buftarg_lock);
1585         list_for_each_entry(btp, &xfs_buftarg_list, bt_list) {
1586                 if (test_bit(XBT_FORCE_SLEEP, &btp->bt_flags))
1587                         continue;
1588                 set_bit(XBT_FORCE_FLUSH, &btp->bt_flags);
1589                 wake_up_process(btp->bt_task);
1590         }
1591         spin_unlock(&xfs_buftarg_lock);
1592         return 0;
1593 }
1594
1595 /*
1596  * Move as many buffers as specified to the supplied list
1597  * idicating if we skipped any buffers to prevent deadlocks.
1598  */
1599 STATIC int
1600 xfs_buf_delwri_split(
1601         xfs_buftarg_t   *target,
1602         struct list_head *list,
1603         unsigned long   age)
1604 {
1605         xfs_buf_t       *bp, *n;
1606         struct list_head *dwq = &target->bt_delwrite_queue;
1607         spinlock_t      *dwlk = &target->bt_delwrite_lock;
1608         int             skipped = 0;
1609         int             force;
1610
1611         force = test_and_clear_bit(XBT_FORCE_FLUSH, &target->bt_flags);
1612         INIT_LIST_HEAD(list);
1613         spin_lock(dwlk);
1614         list_for_each_entry_safe(bp, n, dwq, b_list) {
1615                 XB_TRACE(bp, "walkq1", (long)xfs_buf_ispin(bp));
1616                 ASSERT(bp->b_flags & XBF_DELWRI);
1617
1618                 if (!xfs_buf_ispin(bp) && !xfs_buf_cond_lock(bp)) {
1619                         if (!force &&
1620                             time_before(jiffies, bp->b_queuetime + age)) {
1621                                 xfs_buf_unlock(bp);
1622                                 break;
1623                         }
1624
1625                         bp->b_flags &= ~(XBF_DELWRI|_XBF_DELWRI_Q|
1626                                          _XBF_RUN_QUEUES);
1627                         bp->b_flags |= XBF_WRITE;
1628                         list_move_tail(&bp->b_list, list);
1629                 } else
1630                         skipped++;
1631         }
1632         spin_unlock(dwlk);
1633
1634         return skipped;
1635
1636 }
1637
1638 STATIC int
1639 xfsbufd(
1640         void            *data)
1641 {
1642         struct list_head tmp;
1643         xfs_buftarg_t   *target = (xfs_buftarg_t *)data;
1644         int             count;
1645         xfs_buf_t       *bp;
1646
1647         current->flags |= PF_MEMALLOC;
1648
1649         set_freezable();
1650
1651         do {
1652                 if (unlikely(freezing(current))) {
1653                         set_bit(XBT_FORCE_SLEEP, &target->bt_flags);
1654                         refrigerator();
1655                 } else {
1656                         clear_bit(XBT_FORCE_SLEEP, &target->bt_flags);
1657                 }
1658
1659                 schedule_timeout_interruptible(
1660                         xfs_buf_timer_centisecs * msecs_to_jiffies(10));
1661
1662                 xfs_buf_delwri_split(target, &tmp,
1663                                 xfs_buf_age_centisecs * msecs_to_jiffies(10));
1664
1665                 count = 0;
1666                 while (!list_empty(&tmp)) {
1667                         bp = list_entry(tmp.next, xfs_buf_t, b_list);
1668                         ASSERT(target == bp->b_target);
1669
1670                         list_del_init(&bp->b_list);
1671                         xfs_buf_iostrategy(bp);
1672                         count++;
1673                 }
1674
1675                 if (count)
1676                         blk_run_address_space(target->bt_mapping);
1677
1678         } while (!kthread_should_stop());
1679
1680         return 0;
1681 }
1682
1683 /*
1684  *      Go through all incore buffers, and release buffers if they belong to
1685  *      the given device. This is used in filesystem error handling to
1686  *      preserve the consistency of its metadata.
1687  */
1688 int
1689 xfs_flush_buftarg(
1690         xfs_buftarg_t   *target,
1691         int             wait)
1692 {
1693         struct list_head tmp;
1694         xfs_buf_t       *bp, *n;
1695         int             pincount = 0;
1696
1697         xfs_buf_runall_queues(xfsdatad_workqueue);
1698         xfs_buf_runall_queues(xfslogd_workqueue);
1699
1700         set_bit(XBT_FORCE_FLUSH, &target->bt_flags);
1701         pincount = xfs_buf_delwri_split(target, &tmp, 0);
1702
1703         /*
1704          * Dropped the delayed write list lock, now walk the temporary list
1705          */
1706         list_for_each_entry_safe(bp, n, &tmp, b_list) {
1707                 ASSERT(target == bp->b_target);
1708                 if (wait)
1709                         bp->b_flags &= ~XBF_ASYNC;
1710                 else
1711                         list_del_init(&bp->b_list);
1712
1713                 xfs_buf_iostrategy(bp);
1714         }
1715
1716         if (wait)
1717                 blk_run_address_space(target->bt_mapping);
1718
1719         /*
1720          * Remaining list items must be flushed before returning
1721          */
1722         while (!list_empty(&tmp)) {
1723                 bp = list_entry(tmp.next, xfs_buf_t, b_list);
1724
1725                 list_del_init(&bp->b_list);
1726                 xfs_iowait(bp);
1727                 xfs_buf_relse(bp);
1728         }
1729
1730         return pincount;
1731 }
1732
1733 int __init
1734 xfs_buf_init(void)
1735 {
1736 #ifdef XFS_BUF_TRACE
1737         xfs_buf_trace_buf = ktrace_alloc(XFS_BUF_TRACE_SIZE, KM_NOFS);
1738 #endif
1739
1740         xfs_buf_zone = kmem_zone_init_flags(sizeof(xfs_buf_t), "xfs_buf",
1741                                                 KM_ZONE_HWALIGN, NULL);
1742         if (!xfs_buf_zone)
1743                 goto out_free_trace_buf;
1744
1745         xfslogd_workqueue = create_workqueue("xfslogd");
1746         if (!xfslogd_workqueue)
1747                 goto out_free_buf_zone;
1748
1749         xfsdatad_workqueue = create_workqueue("xfsdatad");
1750         if (!xfsdatad_workqueue)
1751                 goto out_destroy_xfslogd_workqueue;
1752
1753         register_shrinker(&xfs_buf_shake);
1754         return 0;
1755
1756  out_destroy_xfslogd_workqueue:
1757         destroy_workqueue(xfslogd_workqueue);
1758  out_free_buf_zone:
1759         kmem_zone_destroy(xfs_buf_zone);
1760  out_free_trace_buf:
1761 #ifdef XFS_BUF_TRACE
1762         ktrace_free(xfs_buf_trace_buf);
1763 #endif
1764         return -ENOMEM;
1765 }
1766
1767 void
1768 xfs_buf_terminate(void)
1769 {
1770         unregister_shrinker(&xfs_buf_shake);
1771         destroy_workqueue(xfsdatad_workqueue);
1772         destroy_workqueue(xfslogd_workqueue);
1773         kmem_zone_destroy(xfs_buf_zone);
1774 #ifdef XFS_BUF_TRACE
1775         ktrace_free(xfs_buf_trace_buf);
1776 #endif
1777 }
1778
1779 #ifdef CONFIG_KDB_MODULES
1780 struct list_head *
1781 xfs_get_buftarg_list(void)
1782 {
1783         return &xfs_buftarg_list;
1784 }
1785 #endif