]> git.karo-electronics.de Git - mv-sheeva.git/blob - fs/xfs/linux-2.6/xfs_buf.c
e22cce1a9d5dcc65d028bdcba6986f69985155c6
[mv-sheeva.git] / fs / xfs / linux-2.6 / xfs_buf.c
1 /*
2  * Copyright (c) 2000-2005 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 <linux/stddef.h>
19 #include <linux/errno.h>
20 #include <linux/slab.h>
21 #include <linux/pagemap.h>
22 #include <linux/init.h>
23 #include <linux/vmalloc.h>
24 #include <linux/bio.h>
25 #include <linux/sysctl.h>
26 #include <linux/proc_fs.h>
27 #include <linux/workqueue.h>
28 #include <linux/percpu.h>
29 #include <linux/blkdev.h>
30 #include <linux/hash.h>
31 #include <linux/kthread.h>
32 #include "xfs_linux.h"
33
34 STATIC kmem_cache_t *pagebuf_zone;
35 STATIC kmem_shaker_t pagebuf_shake;
36 STATIC int xfsbufd_wakeup(int, gfp_t);
37 STATIC void pagebuf_delwri_queue(xfs_buf_t *, int);
38
39 STATIC struct workqueue_struct *xfslogd_workqueue;
40 struct workqueue_struct *xfsdatad_workqueue;
41
42 #ifdef PAGEBUF_TRACE
43 void
44 pagebuf_trace(
45         xfs_buf_t       *pb,
46         char            *id,
47         void            *data,
48         void            *ra)
49 {
50         ktrace_enter(pagebuf_trace_buf,
51                 pb, id,
52                 (void *)(unsigned long)pb->pb_flags,
53                 (void *)(unsigned long)pb->pb_hold.counter,
54                 (void *)(unsigned long)pb->pb_sema.count.counter,
55                 (void *)current,
56                 data, ra,
57                 (void *)(unsigned long)((pb->pb_file_offset>>32) & 0xffffffff),
58                 (void *)(unsigned long)(pb->pb_file_offset & 0xffffffff),
59                 (void *)(unsigned long)pb->pb_buffer_length,
60                 NULL, NULL, NULL, NULL, NULL);
61 }
62 ktrace_t *pagebuf_trace_buf;
63 #define PAGEBUF_TRACE_SIZE      4096
64 #define PB_TRACE(pb, id, data)  \
65         pagebuf_trace(pb, id, (void *)data, (void *)__builtin_return_address(0))
66 #else
67 #define PB_TRACE(pb, id, data)  do { } while (0)
68 #endif
69
70 #ifdef PAGEBUF_LOCK_TRACKING
71 # define PB_SET_OWNER(pb)       ((pb)->pb_last_holder = current->pid)
72 # define PB_CLEAR_OWNER(pb)     ((pb)->pb_last_holder = -1)
73 # define PB_GET_OWNER(pb)       ((pb)->pb_last_holder)
74 #else
75 # define PB_SET_OWNER(pb)       do { } while (0)
76 # define PB_CLEAR_OWNER(pb)     do { } while (0)
77 # define PB_GET_OWNER(pb)       do { } while (0)
78 #endif
79
80 #define pb_to_gfp(flags) \
81         ((((flags) & PBF_READ_AHEAD) ? __GFP_NORETRY : \
82           ((flags) & PBF_DONT_BLOCK) ? GFP_NOFS : GFP_KERNEL) | __GFP_NOWARN)
83
84 #define pb_to_km(flags) \
85          (((flags) & PBF_DONT_BLOCK) ? KM_NOFS : KM_SLEEP)
86
87 #define pagebuf_allocate(flags) \
88         kmem_zone_alloc(pagebuf_zone, pb_to_km(flags))
89 #define pagebuf_deallocate(pb) \
90         kmem_zone_free(pagebuf_zone, (pb));
91
92 /*
93  * Page Region interfaces.
94  *
95  * For pages in filesystems where the blocksize is smaller than the
96  * pagesize, we use the page->private field (long) to hold a bitmap
97  * of uptodate regions within the page.
98  *
99  * Each such region is "bytes per page / bits per long" bytes long.
100  *
101  * NBPPR == number-of-bytes-per-page-region
102  * BTOPR == bytes-to-page-region (rounded up)
103  * BTOPRT == bytes-to-page-region-truncated (rounded down)
104  */
105 #if (BITS_PER_LONG == 32)
106 #define PRSHIFT         (PAGE_CACHE_SHIFT - 5)  /* (32 == 1<<5) */
107 #elif (BITS_PER_LONG == 64)
108 #define PRSHIFT         (PAGE_CACHE_SHIFT - 6)  /* (64 == 1<<6) */
109 #else
110 #error BITS_PER_LONG must be 32 or 64
111 #endif
112 #define NBPPR           (PAGE_CACHE_SIZE/BITS_PER_LONG)
113 #define BTOPR(b)        (((unsigned int)(b) + (NBPPR - 1)) >> PRSHIFT)
114 #define BTOPRT(b)       (((unsigned int)(b) >> PRSHIFT))
115
116 STATIC unsigned long
117 page_region_mask(
118         size_t          offset,
119         size_t          length)
120 {
121         unsigned long   mask;
122         int             first, final;
123
124         first = BTOPR(offset);
125         final = BTOPRT(offset + length - 1);
126         first = min(first, final);
127
128         mask = ~0UL;
129         mask <<= BITS_PER_LONG - (final - first);
130         mask >>= BITS_PER_LONG - (final);
131
132         ASSERT(offset + length <= PAGE_CACHE_SIZE);
133         ASSERT((final - first) < BITS_PER_LONG && (final - first) >= 0);
134
135         return mask;
136 }
137
138 STATIC inline void
139 set_page_region(
140         struct page     *page,
141         size_t          offset,
142         size_t          length)
143 {
144         set_page_private(page,
145                 page_private(page) | page_region_mask(offset, length));
146         if (page_private(page) == ~0UL)
147                 SetPageUptodate(page);
148 }
149
150 STATIC inline int
151 test_page_region(
152         struct page     *page,
153         size_t          offset,
154         size_t          length)
155 {
156         unsigned long   mask = page_region_mask(offset, length);
157
158         return (mask && (page_private(page) & mask) == mask);
159 }
160
161 /*
162  * Mapping of multi-page buffers into contiguous virtual space
163  */
164
165 typedef struct a_list {
166         void            *vm_addr;
167         struct a_list   *next;
168 } a_list_t;
169
170 STATIC a_list_t         *as_free_head;
171 STATIC int              as_list_len;
172 STATIC DEFINE_SPINLOCK(as_lock);
173
174 /*
175  * Try to batch vunmaps because they are costly.
176  */
177 STATIC void
178 free_address(
179         void            *addr)
180 {
181         a_list_t        *aentry;
182
183         aentry = kmalloc(sizeof(a_list_t), GFP_ATOMIC & ~__GFP_HIGH);
184         if (likely(aentry)) {
185                 spin_lock(&as_lock);
186                 aentry->next = as_free_head;
187                 aentry->vm_addr = addr;
188                 as_free_head = aentry;
189                 as_list_len++;
190                 spin_unlock(&as_lock);
191         } else {
192                 vunmap(addr);
193         }
194 }
195
196 STATIC void
197 purge_addresses(void)
198 {
199         a_list_t        *aentry, *old;
200
201         if (as_free_head == NULL)
202                 return;
203
204         spin_lock(&as_lock);
205         aentry = as_free_head;
206         as_free_head = NULL;
207         as_list_len = 0;
208         spin_unlock(&as_lock);
209
210         while ((old = aentry) != NULL) {
211                 vunmap(aentry->vm_addr);
212                 aentry = aentry->next;
213                 kfree(old);
214         }
215 }
216
217 /*
218  *      Internal pagebuf object manipulation
219  */
220
221 STATIC void
222 _pagebuf_initialize(
223         xfs_buf_t               *pb,
224         xfs_buftarg_t           *target,
225         loff_t                  range_base,
226         size_t                  range_length,
227         page_buf_flags_t        flags)
228 {
229         /*
230          * We don't want certain flags to appear in pb->pb_flags.
231          */
232         flags &= ~(PBF_LOCK|PBF_MAPPED|PBF_DONT_BLOCK|PBF_READ_AHEAD);
233
234         memset(pb, 0, sizeof(xfs_buf_t));
235         atomic_set(&pb->pb_hold, 1);
236         init_MUTEX_LOCKED(&pb->pb_iodonesema);
237         INIT_LIST_HEAD(&pb->pb_list);
238         INIT_LIST_HEAD(&pb->pb_hash_list);
239         init_MUTEX_LOCKED(&pb->pb_sema); /* held, no waiters */
240         PB_SET_OWNER(pb);
241         pb->pb_target = target;
242         pb->pb_file_offset = range_base;
243         /*
244          * Set buffer_length and count_desired to the same value initially.
245          * I/O routines should use count_desired, which will be the same in
246          * most cases but may be reset (e.g. XFS recovery).
247          */
248         pb->pb_buffer_length = pb->pb_count_desired = range_length;
249         pb->pb_flags = flags;
250         pb->pb_bn = XFS_BUF_DADDR_NULL;
251         atomic_set(&pb->pb_pin_count, 0);
252         init_waitqueue_head(&pb->pb_waiters);
253
254         XFS_STATS_INC(pb_create);
255         PB_TRACE(pb, "initialize", target);
256 }
257
258 /*
259  * Allocate a page array capable of holding a specified number
260  * of pages, and point the page buf at it.
261  */
262 STATIC int
263 _pagebuf_get_pages(
264         xfs_buf_t               *pb,
265         int                     page_count,
266         page_buf_flags_t        flags)
267 {
268         /* Make sure that we have a page list */
269         if (pb->pb_pages == NULL) {
270                 pb->pb_offset = page_buf_poff(pb->pb_file_offset);
271                 pb->pb_page_count = page_count;
272                 if (page_count <= PB_PAGES) {
273                         pb->pb_pages = pb->pb_page_array;
274                 } else {
275                         pb->pb_pages = kmem_alloc(sizeof(struct page *) *
276                                         page_count, pb_to_km(flags));
277                         if (pb->pb_pages == NULL)
278                                 return -ENOMEM;
279                 }
280                 memset(pb->pb_pages, 0, sizeof(struct page *) * page_count);
281         }
282         return 0;
283 }
284
285 /*
286  *      Frees pb_pages if it was malloced.
287  */
288 STATIC void
289 _pagebuf_free_pages(
290         xfs_buf_t       *bp)
291 {
292         if (bp->pb_pages != bp->pb_page_array) {
293                 kmem_free(bp->pb_pages,
294                           bp->pb_page_count * sizeof(struct page *));
295         }
296 }
297
298 /*
299  *      Releases the specified buffer.
300  *
301  *      The modification state of any associated pages is left unchanged.
302  *      The buffer most not be on any hash - use pagebuf_rele instead for
303  *      hashed and refcounted buffers
304  */
305 void
306 pagebuf_free(
307         xfs_buf_t               *bp)
308 {
309         PB_TRACE(bp, "free", 0);
310
311         ASSERT(list_empty(&bp->pb_hash_list));
312
313         if (bp->pb_flags & _PBF_PAGE_CACHE) {
314                 uint            i;
315
316                 if ((bp->pb_flags & PBF_MAPPED) && (bp->pb_page_count > 1))
317                         free_address(bp->pb_addr - bp->pb_offset);
318
319                 for (i = 0; i < bp->pb_page_count; i++)
320                         page_cache_release(bp->pb_pages[i]);
321                 _pagebuf_free_pages(bp);
322         } else if (bp->pb_flags & _PBF_KMEM_ALLOC) {
323                  /*
324                   * XXX(hch): bp->pb_count_desired might be incorrect (see
325                   * pagebuf_associate_memory for details), but fortunately
326                   * the Linux version of kmem_free ignores the len argument..
327                   */
328                 kmem_free(bp->pb_addr, bp->pb_count_desired);
329                 _pagebuf_free_pages(bp);
330         }
331
332         pagebuf_deallocate(bp);
333 }
334
335 /*
336  *      Finds all pages for buffer in question and builds it's page list.
337  */
338 STATIC int
339 _pagebuf_lookup_pages(
340         xfs_buf_t               *bp,
341         uint                    flags)
342 {
343         struct address_space    *mapping = bp->pb_target->pbr_mapping;
344         size_t                  blocksize = bp->pb_target->pbr_bsize;
345         size_t                  size = bp->pb_count_desired;
346         size_t                  nbytes, offset;
347         gfp_t                   gfp_mask = pb_to_gfp(flags);
348         unsigned short          page_count, i;
349         pgoff_t                 first;
350         loff_t                  end;
351         int                     error;
352
353         end = bp->pb_file_offset + bp->pb_buffer_length;
354         page_count = page_buf_btoc(end) - page_buf_btoct(bp->pb_file_offset);
355
356         error = _pagebuf_get_pages(bp, page_count, flags);
357         if (unlikely(error))
358                 return error;
359         bp->pb_flags |= _PBF_PAGE_CACHE;
360
361         offset = bp->pb_offset;
362         first = bp->pb_file_offset >> PAGE_CACHE_SHIFT;
363
364         for (i = 0; i < bp->pb_page_count; i++) {
365                 struct page     *page;
366                 uint            retries = 0;
367
368               retry:
369                 page = find_or_create_page(mapping, first + i, gfp_mask);
370                 if (unlikely(page == NULL)) {
371                         if (flags & PBF_READ_AHEAD) {
372                                 bp->pb_page_count = i;
373                                 for (i = 0; i < bp->pb_page_count; i++)
374                                         unlock_page(bp->pb_pages[i]);
375                                 return -ENOMEM;
376                         }
377
378                         /*
379                          * This could deadlock.
380                          *
381                          * But until all the XFS lowlevel code is revamped to
382                          * handle buffer allocation failures we can't do much.
383                          */
384                         if (!(++retries % 100))
385                                 printk(KERN_ERR
386                                         "XFS: possible memory allocation "
387                                         "deadlock in %s (mode:0x%x)\n",
388                                         __FUNCTION__, gfp_mask);
389
390                         XFS_STATS_INC(pb_page_retries);
391                         xfsbufd_wakeup(0, gfp_mask);
392                         blk_congestion_wait(WRITE, HZ/50);
393                         goto retry;
394                 }
395
396                 XFS_STATS_INC(pb_page_found);
397
398                 nbytes = min_t(size_t, size, PAGE_CACHE_SIZE - offset);
399                 size -= nbytes;
400
401                 if (!PageUptodate(page)) {
402                         page_count--;
403                         if (blocksize >= PAGE_CACHE_SIZE) {
404                                 if (flags & PBF_READ)
405                                         bp->pb_locked = 1;
406                         } else if (!PagePrivate(page)) {
407                                 if (test_page_region(page, offset, nbytes))
408                                         page_count++;
409                         }
410                 }
411
412                 bp->pb_pages[i] = page;
413                 offset = 0;
414         }
415
416         if (!bp->pb_locked) {
417                 for (i = 0; i < bp->pb_page_count; i++)
418                         unlock_page(bp->pb_pages[i]);
419         }
420
421         if (page_count == bp->pb_page_count)
422                 bp->pb_flags |= PBF_DONE;
423
424         PB_TRACE(bp, "lookup_pages", (long)page_count);
425         return error;
426 }
427
428 /*
429  *      Map buffer into kernel address-space if nessecary.
430  */
431 STATIC int
432 _pagebuf_map_pages(
433         xfs_buf_t               *bp,
434         uint                    flags)
435 {
436         /* A single page buffer is always mappable */
437         if (bp->pb_page_count == 1) {
438                 bp->pb_addr = page_address(bp->pb_pages[0]) + bp->pb_offset;
439                 bp->pb_flags |= PBF_MAPPED;
440         } else if (flags & PBF_MAPPED) {
441                 if (as_list_len > 64)
442                         purge_addresses();
443                 bp->pb_addr = vmap(bp->pb_pages, bp->pb_page_count,
444                                 VM_MAP, PAGE_KERNEL);
445                 if (unlikely(bp->pb_addr == NULL))
446                         return -ENOMEM;
447                 bp->pb_addr += bp->pb_offset;
448                 bp->pb_flags |= PBF_MAPPED;
449         }
450
451         return 0;
452 }
453
454 /*
455  *      Finding and Reading Buffers
456  */
457
458 /*
459  *      _pagebuf_find
460  *
461  *      Looks up, and creates if absent, a lockable buffer for
462  *      a given range of an inode.  The buffer is returned
463  *      locked.  If other overlapping buffers exist, they are
464  *      released before the new buffer is created and locked,
465  *      which may imply that this call will block until those buffers
466  *      are unlocked.  No I/O is implied by this call.
467  */
468 xfs_buf_t *
469 _pagebuf_find(
470         xfs_buftarg_t           *btp,   /* block device target          */
471         loff_t                  ioff,   /* starting offset of range     */
472         size_t                  isize,  /* length of range              */
473         page_buf_flags_t        flags,  /* PBF_TRYLOCK                  */
474         xfs_buf_t               *new_pb)/* newly allocated buffer       */
475 {
476         loff_t                  range_base;
477         size_t                  range_length;
478         xfs_bufhash_t           *hash;
479         xfs_buf_t               *pb, *n;
480
481         range_base = (ioff << BBSHIFT);
482         range_length = (isize << BBSHIFT);
483
484         /* Check for IOs smaller than the sector size / not sector aligned */
485         ASSERT(!(range_length < (1 << btp->pbr_sshift)));
486         ASSERT(!(range_base & (loff_t)btp->pbr_smask));
487
488         hash = &btp->bt_hash[hash_long((unsigned long)ioff, btp->bt_hashshift)];
489
490         spin_lock(&hash->bh_lock);
491
492         list_for_each_entry_safe(pb, n, &hash->bh_list, pb_hash_list) {
493                 ASSERT(btp == pb->pb_target);
494                 if (pb->pb_file_offset == range_base &&
495                     pb->pb_buffer_length == range_length) {
496                         /*
497                          * If we look at something bring it to the
498                          * front of the list for next time.
499                          */
500                         atomic_inc(&pb->pb_hold);
501                         list_move(&pb->pb_hash_list, &hash->bh_list);
502                         goto found;
503                 }
504         }
505
506         /* No match found */
507         if (new_pb) {
508                 _pagebuf_initialize(new_pb, btp, range_base,
509                                 range_length, flags);
510                 new_pb->pb_hash = hash;
511                 list_add(&new_pb->pb_hash_list, &hash->bh_list);
512         } else {
513                 XFS_STATS_INC(pb_miss_locked);
514         }
515
516         spin_unlock(&hash->bh_lock);
517         return new_pb;
518
519 found:
520         spin_unlock(&hash->bh_lock);
521
522         /* Attempt to get the semaphore without sleeping,
523          * if this does not work then we need to drop the
524          * spinlock and do a hard attempt on the semaphore.
525          */
526         if (down_trylock(&pb->pb_sema)) {
527                 if (!(flags & PBF_TRYLOCK)) {
528                         /* wait for buffer ownership */
529                         PB_TRACE(pb, "get_lock", 0);
530                         pagebuf_lock(pb);
531                         XFS_STATS_INC(pb_get_locked_waited);
532                 } else {
533                         /* We asked for a trylock and failed, no need
534                          * to look at file offset and length here, we
535                          * know that this pagebuf at least overlaps our
536                          * pagebuf and is locked, therefore our buffer
537                          * either does not exist, or is this buffer
538                          */
539
540                         pagebuf_rele(pb);
541                         XFS_STATS_INC(pb_busy_locked);
542                         return (NULL);
543                 }
544         } else {
545                 /* trylock worked */
546                 PB_SET_OWNER(pb);
547         }
548
549         if (pb->pb_flags & PBF_STALE) {
550                 ASSERT((pb->pb_flags & _PBF_DELWRI_Q) == 0);
551                 pb->pb_flags &= PBF_MAPPED;
552         }
553         PB_TRACE(pb, "got_lock", 0);
554         XFS_STATS_INC(pb_get_locked);
555         return (pb);
556 }
557
558 /*
559  *      xfs_buf_get_flags assembles a buffer covering the specified range.
560  *
561  *      Storage in memory for all portions of the buffer will be allocated,
562  *      although backing storage may not be.
563  */
564 xfs_buf_t *
565 xfs_buf_get_flags(                      /* allocate a buffer            */
566         xfs_buftarg_t           *target,/* target for buffer            */
567         loff_t                  ioff,   /* starting offset of range     */
568         size_t                  isize,  /* length of range              */
569         page_buf_flags_t        flags)  /* PBF_TRYLOCK                  */
570 {
571         xfs_buf_t               *pb, *new_pb;
572         int                     error = 0, i;
573
574         new_pb = pagebuf_allocate(flags);
575         if (unlikely(!new_pb))
576                 return NULL;
577
578         pb = _pagebuf_find(target, ioff, isize, flags, new_pb);
579         if (pb == new_pb) {
580                 error = _pagebuf_lookup_pages(pb, flags);
581                 if (error)
582                         goto no_buffer;
583         } else {
584                 pagebuf_deallocate(new_pb);
585                 if (unlikely(pb == NULL))
586                         return NULL;
587         }
588
589         for (i = 0; i < pb->pb_page_count; i++)
590                 mark_page_accessed(pb->pb_pages[i]);
591
592         if (!(pb->pb_flags & PBF_MAPPED)) {
593                 error = _pagebuf_map_pages(pb, flags);
594                 if (unlikely(error)) {
595                         printk(KERN_WARNING "%s: failed to map pages\n",
596                                         __FUNCTION__);
597                         goto no_buffer;
598                 }
599         }
600
601         XFS_STATS_INC(pb_get);
602
603         /*
604          * Always fill in the block number now, the mapped cases can do
605          * their own overlay of this later.
606          */
607         pb->pb_bn = ioff;
608         pb->pb_count_desired = pb->pb_buffer_length;
609
610         PB_TRACE(pb, "get", (unsigned long)flags);
611         return pb;
612
613  no_buffer:
614         if (flags & (PBF_LOCK | PBF_TRYLOCK))
615                 pagebuf_unlock(pb);
616         pagebuf_rele(pb);
617         return NULL;
618 }
619
620 xfs_buf_t *
621 xfs_buf_read_flags(
622         xfs_buftarg_t           *target,
623         loff_t                  ioff,
624         size_t                  isize,
625         page_buf_flags_t        flags)
626 {
627         xfs_buf_t               *pb;
628
629         flags |= PBF_READ;
630
631         pb = xfs_buf_get_flags(target, ioff, isize, flags);
632         if (pb) {
633                 if (!XFS_BUF_ISDONE(pb)) {
634                         PB_TRACE(pb, "read", (unsigned long)flags);
635                         XFS_STATS_INC(pb_get_read);
636                         pagebuf_iostart(pb, flags);
637                 } else if (flags & PBF_ASYNC) {
638                         PB_TRACE(pb, "read_async", (unsigned long)flags);
639                         /*
640                          * Read ahead call which is already satisfied,
641                          * drop the buffer
642                          */
643                         goto no_buffer;
644                 } else {
645                         PB_TRACE(pb, "read_done", (unsigned long)flags);
646                         /* We do not want read in the flags */
647                         pb->pb_flags &= ~PBF_READ;
648                 }
649         }
650
651         return pb;
652
653  no_buffer:
654         if (flags & (PBF_LOCK | PBF_TRYLOCK))
655                 pagebuf_unlock(pb);
656         pagebuf_rele(pb);
657         return NULL;
658 }
659
660 /*
661  * If we are not low on memory then do the readahead in a deadlock
662  * safe manner.
663  */
664 void
665 pagebuf_readahead(
666         xfs_buftarg_t           *target,
667         loff_t                  ioff,
668         size_t                  isize,
669         page_buf_flags_t        flags)
670 {
671         struct backing_dev_info *bdi;
672
673         bdi = target->pbr_mapping->backing_dev_info;
674         if (bdi_read_congested(bdi))
675                 return;
676
677         flags |= (PBF_TRYLOCK|PBF_ASYNC|PBF_READ_AHEAD);
678         xfs_buf_read_flags(target, ioff, isize, flags);
679 }
680
681 xfs_buf_t *
682 pagebuf_get_empty(
683         size_t                  len,
684         xfs_buftarg_t           *target)
685 {
686         xfs_buf_t               *pb;
687
688         pb = pagebuf_allocate(0);
689         if (pb)
690                 _pagebuf_initialize(pb, target, 0, len, 0);
691         return pb;
692 }
693
694 static inline struct page *
695 mem_to_page(
696         void                    *addr)
697 {
698         if (((unsigned long)addr < VMALLOC_START) ||
699             ((unsigned long)addr >= VMALLOC_END)) {
700                 return virt_to_page(addr);
701         } else {
702                 return vmalloc_to_page(addr);
703         }
704 }
705
706 int
707 pagebuf_associate_memory(
708         xfs_buf_t               *pb,
709         void                    *mem,
710         size_t                  len)
711 {
712         int                     rval;
713         int                     i = 0;
714         size_t                  ptr;
715         size_t                  end, end_cur;
716         off_t                   offset;
717         int                     page_count;
718
719         page_count = PAGE_CACHE_ALIGN(len) >> PAGE_CACHE_SHIFT;
720         offset = (off_t) mem - ((off_t)mem & PAGE_CACHE_MASK);
721         if (offset && (len > PAGE_CACHE_SIZE))
722                 page_count++;
723
724         /* Free any previous set of page pointers */
725         if (pb->pb_pages)
726                 _pagebuf_free_pages(pb);
727
728         pb->pb_pages = NULL;
729         pb->pb_addr = mem;
730
731         rval = _pagebuf_get_pages(pb, page_count, 0);
732         if (rval)
733                 return rval;
734
735         pb->pb_offset = offset;
736         ptr = (size_t) mem & PAGE_CACHE_MASK;
737         end = PAGE_CACHE_ALIGN((size_t) mem + len);
738         end_cur = end;
739         /* set up first page */
740         pb->pb_pages[0] = mem_to_page(mem);
741
742         ptr += PAGE_CACHE_SIZE;
743         pb->pb_page_count = ++i;
744         while (ptr < end) {
745                 pb->pb_pages[i] = mem_to_page((void *)ptr);
746                 pb->pb_page_count = ++i;
747                 ptr += PAGE_CACHE_SIZE;
748         }
749         pb->pb_locked = 0;
750
751         pb->pb_count_desired = pb->pb_buffer_length = len;
752         pb->pb_flags |= PBF_MAPPED;
753
754         return 0;
755 }
756
757 xfs_buf_t *
758 pagebuf_get_no_daddr(
759         size_t                  len,
760         xfs_buftarg_t           *target)
761 {
762         size_t                  malloc_len = len;
763         xfs_buf_t               *bp;
764         void                    *data;
765         int                     error;
766
767         bp = pagebuf_allocate(0);
768         if (unlikely(bp == NULL))
769                 goto fail;
770         _pagebuf_initialize(bp, target, 0, len, 0);
771
772  try_again:
773         data = kmem_alloc(malloc_len, KM_SLEEP | KM_MAYFAIL);
774         if (unlikely(data == NULL))
775                 goto fail_free_buf;
776
777         /* check whether alignment matches.. */
778         if ((__psunsigned_t)data !=
779             ((__psunsigned_t)data & ~target->pbr_smask)) {
780                 /* .. else double the size and try again */
781                 kmem_free(data, malloc_len);
782                 malloc_len <<= 1;
783                 goto try_again;
784         }
785
786         error = pagebuf_associate_memory(bp, data, len);
787         if (error)
788                 goto fail_free_mem;
789         bp->pb_flags |= _PBF_KMEM_ALLOC;
790
791         pagebuf_unlock(bp);
792
793         PB_TRACE(bp, "no_daddr", data);
794         return bp;
795  fail_free_mem:
796         kmem_free(data, malloc_len);
797  fail_free_buf:
798         pagebuf_free(bp);
799  fail:
800         return NULL;
801 }
802
803 /*
804  *      pagebuf_hold
805  *
806  *      Increment reference count on buffer, to hold the buffer concurrently
807  *      with another thread which may release (free) the buffer asynchronously.
808  *
809  *      Must hold the buffer already to call this function.
810  */
811 void
812 pagebuf_hold(
813         xfs_buf_t               *pb)
814 {
815         atomic_inc(&pb->pb_hold);
816         PB_TRACE(pb, "hold", 0);
817 }
818
819 /*
820  *      pagebuf_rele
821  *
822  *      pagebuf_rele releases a hold on the specified buffer.  If the
823  *      the hold count is 1, pagebuf_rele calls pagebuf_free.
824  */
825 void
826 pagebuf_rele(
827         xfs_buf_t               *pb)
828 {
829         xfs_bufhash_t           *hash = pb->pb_hash;
830
831         PB_TRACE(pb, "rele", pb->pb_relse);
832
833         /*
834          * pagebuf_lookup buffers are not hashed, not delayed write,
835          * and don't have their own release routines.  Special case.
836          */
837         if (unlikely(!hash)) {
838                 ASSERT(!pb->pb_relse);
839                 if (atomic_dec_and_test(&pb->pb_hold))
840                         xfs_buf_free(pb);
841                 return;
842         }
843
844         if (atomic_dec_and_lock(&pb->pb_hold, &hash->bh_lock)) {
845                 int             do_free = 1;
846
847                 if (pb->pb_relse) {
848                         atomic_inc(&pb->pb_hold);
849                         spin_unlock(&hash->bh_lock);
850                         (*(pb->pb_relse)) (pb);
851                         spin_lock(&hash->bh_lock);
852                         do_free = 0;
853                 }
854
855                 if (pb->pb_flags & PBF_FS_MANAGED) {
856                         do_free = 0;
857                 }
858
859                 if (do_free) {
860                         ASSERT((pb->pb_flags & (PBF_DELWRI|_PBF_DELWRI_Q)) == 0);
861                         list_del_init(&pb->pb_hash_list);
862                         spin_unlock(&hash->bh_lock);
863                         pagebuf_free(pb);
864                 } else {
865                         spin_unlock(&hash->bh_lock);
866                 }
867         } else {
868                 /*
869                  * Catch reference count leaks
870                  */
871                 ASSERT(atomic_read(&pb->pb_hold) >= 0);
872         }
873 }
874
875
876 /*
877  *      Mutual exclusion on buffers.  Locking model:
878  *
879  *      Buffers associated with inodes for which buffer locking
880  *      is not enabled are not protected by semaphores, and are
881  *      assumed to be exclusively owned by the caller.  There is a
882  *      spinlock in the buffer, used by the caller when concurrent
883  *      access is possible.
884  */
885
886 /*
887  *      pagebuf_cond_lock
888  *
889  *      pagebuf_cond_lock locks a buffer object, if it is not already locked.
890  *      Note that this in no way
891  *      locks the underlying pages, so it is only useful for synchronizing
892  *      concurrent use of page buffer objects, not for synchronizing independent
893  *      access to the underlying pages.
894  */
895 int
896 pagebuf_cond_lock(                      /* lock buffer, if not locked   */
897                                         /* returns -EBUSY if locked)    */
898         xfs_buf_t               *pb)
899 {
900         int                     locked;
901
902         locked = down_trylock(&pb->pb_sema) == 0;
903         if (locked) {
904                 PB_SET_OWNER(pb);
905         }
906         PB_TRACE(pb, "cond_lock", (long)locked);
907         return(locked ? 0 : -EBUSY);
908 }
909
910 #if defined(DEBUG) || defined(XFS_BLI_TRACE)
911 /*
912  *      pagebuf_lock_value
913  *
914  *      Return lock value for a pagebuf
915  */
916 int
917 pagebuf_lock_value(
918         xfs_buf_t               *pb)
919 {
920         return(atomic_read(&pb->pb_sema.count));
921 }
922 #endif
923
924 /*
925  *      pagebuf_lock
926  *
927  *      pagebuf_lock locks a buffer object.  Note that this in no way
928  *      locks the underlying pages, so it is only useful for synchronizing
929  *      concurrent use of page buffer objects, not for synchronizing independent
930  *      access to the underlying pages.
931  */
932 int
933 pagebuf_lock(
934         xfs_buf_t               *pb)
935 {
936         PB_TRACE(pb, "lock", 0);
937         if (atomic_read(&pb->pb_io_remaining))
938                 blk_run_address_space(pb->pb_target->pbr_mapping);
939         down(&pb->pb_sema);
940         PB_SET_OWNER(pb);
941         PB_TRACE(pb, "locked", 0);
942         return 0;
943 }
944
945 /*
946  *      pagebuf_unlock
947  *
948  *      pagebuf_unlock releases the lock on the buffer object created by
949  *      pagebuf_lock or pagebuf_cond_lock (not any pinning of underlying pages
950  *      created by pagebuf_pin).
951  *
952  *      If the buffer is marked delwri but is not queued, do so before we
953  *      unlock the buffer as we need to set flags correctly. We also need to
954  *      take a reference for the delwri queue because the unlocker is going to
955  *      drop their's and they don't know we just queued it.
956  */
957 void
958 pagebuf_unlock(                         /* unlock buffer                */
959         xfs_buf_t               *pb)    /* buffer to unlock             */
960 {
961         if ((pb->pb_flags & (PBF_DELWRI|_PBF_DELWRI_Q)) == PBF_DELWRI) {
962                 atomic_inc(&pb->pb_hold);
963                 pb->pb_flags |= PBF_ASYNC;
964                 pagebuf_delwri_queue(pb, 0);
965         }
966
967         PB_CLEAR_OWNER(pb);
968         up(&pb->pb_sema);
969         PB_TRACE(pb, "unlock", 0);
970 }
971
972
973 /*
974  *      Pinning Buffer Storage in Memory
975  */
976
977 /*
978  *      pagebuf_pin
979  *
980  *      pagebuf_pin locks all of the memory represented by a buffer in
981  *      memory.  Multiple calls to pagebuf_pin and pagebuf_unpin, for
982  *      the same or different buffers affecting a given page, will
983  *      properly count the number of outstanding "pin" requests.  The
984  *      buffer may be released after the pagebuf_pin and a different
985  *      buffer used when calling pagebuf_unpin, if desired.
986  *      pagebuf_pin should be used by the file system when it wants be
987  *      assured that no attempt will be made to force the affected
988  *      memory to disk.  It does not assure that a given logical page
989  *      will not be moved to a different physical page.
990  */
991 void
992 pagebuf_pin(
993         xfs_buf_t               *pb)
994 {
995         atomic_inc(&pb->pb_pin_count);
996         PB_TRACE(pb, "pin", (long)pb->pb_pin_count.counter);
997 }
998
999 /*
1000  *      pagebuf_unpin
1001  *
1002  *      pagebuf_unpin reverses the locking of memory performed by
1003  *      pagebuf_pin.  Note that both functions affected the logical
1004  *      pages associated with the buffer, not the buffer itself.
1005  */
1006 void
1007 pagebuf_unpin(
1008         xfs_buf_t               *pb)
1009 {
1010         if (atomic_dec_and_test(&pb->pb_pin_count)) {
1011                 wake_up_all(&pb->pb_waiters);
1012         }
1013         PB_TRACE(pb, "unpin", (long)pb->pb_pin_count.counter);
1014 }
1015
1016 int
1017 pagebuf_ispin(
1018         xfs_buf_t               *pb)
1019 {
1020         return atomic_read(&pb->pb_pin_count);
1021 }
1022
1023 /*
1024  *      pagebuf_wait_unpin
1025  *
1026  *      pagebuf_wait_unpin waits until all of the memory associated
1027  *      with the buffer is not longer locked in memory.  It returns
1028  *      immediately if none of the affected pages are locked.
1029  */
1030 static inline void
1031 _pagebuf_wait_unpin(
1032         xfs_buf_t               *pb)
1033 {
1034         DECLARE_WAITQUEUE       (wait, current);
1035
1036         if (atomic_read(&pb->pb_pin_count) == 0)
1037                 return;
1038
1039         add_wait_queue(&pb->pb_waiters, &wait);
1040         for (;;) {
1041                 set_current_state(TASK_UNINTERRUPTIBLE);
1042                 if (atomic_read(&pb->pb_pin_count) == 0)
1043                         break;
1044                 if (atomic_read(&pb->pb_io_remaining))
1045                         blk_run_address_space(pb->pb_target->pbr_mapping);
1046                 schedule();
1047         }
1048         remove_wait_queue(&pb->pb_waiters, &wait);
1049         set_current_state(TASK_RUNNING);
1050 }
1051
1052 /*
1053  *      Buffer Utility Routines
1054  */
1055
1056 /*
1057  *      pagebuf_iodone
1058  *
1059  *      pagebuf_iodone marks a buffer for which I/O is in progress
1060  *      done with respect to that I/O.  The pb_iodone routine, if
1061  *      present, will be called as a side-effect.
1062  */
1063 STATIC void
1064 pagebuf_iodone_work(
1065         void                    *v)
1066 {
1067         xfs_buf_t               *bp = (xfs_buf_t *)v;
1068
1069         if (bp->pb_iodone)
1070                 (*(bp->pb_iodone))(bp);
1071         else if (bp->pb_flags & PBF_ASYNC)
1072                 xfs_buf_relse(bp);
1073 }
1074
1075 void
1076 pagebuf_iodone(
1077         xfs_buf_t               *pb,
1078         int                     schedule)
1079 {
1080         pb->pb_flags &= ~(PBF_READ | PBF_WRITE);
1081         if (pb->pb_error == 0)
1082                 pb->pb_flags |= PBF_DONE;
1083
1084         PB_TRACE(pb, "iodone", pb->pb_iodone);
1085
1086         if ((pb->pb_iodone) || (pb->pb_flags & PBF_ASYNC)) {
1087                 if (schedule) {
1088                         INIT_WORK(&pb->pb_iodone_work, pagebuf_iodone_work, pb);
1089                         queue_work(xfslogd_workqueue, &pb->pb_iodone_work);
1090                 } else {
1091                         pagebuf_iodone_work(pb);
1092                 }
1093         } else {
1094                 up(&pb->pb_iodonesema);
1095         }
1096 }
1097
1098 /*
1099  *      pagebuf_ioerror
1100  *
1101  *      pagebuf_ioerror sets the error code for a buffer.
1102  */
1103 void
1104 pagebuf_ioerror(                        /* mark/clear buffer error flag */
1105         xfs_buf_t               *pb,    /* buffer to mark               */
1106         int                     error)  /* error to store (0 if none)   */
1107 {
1108         ASSERT(error >= 0 && error <= 0xffff);
1109         pb->pb_error = (unsigned short)error;
1110         PB_TRACE(pb, "ioerror", (unsigned long)error);
1111 }
1112
1113 /*
1114  *      pagebuf_iostart
1115  *
1116  *      pagebuf_iostart initiates I/O on a buffer, based on the flags supplied.
1117  *      If necessary, it will arrange for any disk space allocation required,
1118  *      and it will break up the request if the block mappings require it.
1119  *      The pb_iodone routine in the buffer supplied will only be called
1120  *      when all of the subsidiary I/O requests, if any, have been completed.
1121  *      pagebuf_iostart calls the pagebuf_ioinitiate routine or
1122  *      pagebuf_iorequest, if the former routine is not defined, to start
1123  *      the I/O on a given low-level request.
1124  */
1125 int
1126 pagebuf_iostart(                        /* start I/O on a buffer          */
1127         xfs_buf_t               *pb,    /* buffer to start                */
1128         page_buf_flags_t        flags)  /* PBF_LOCK, PBF_ASYNC, PBF_READ, */
1129                                         /* PBF_WRITE, PBF_DELWRI,         */
1130                                         /* PBF_DONT_BLOCK                 */
1131 {
1132         int                     status = 0;
1133
1134         PB_TRACE(pb, "iostart", (unsigned long)flags);
1135
1136         if (flags & PBF_DELWRI) {
1137                 pb->pb_flags &= ~(PBF_READ | PBF_WRITE | PBF_ASYNC);
1138                 pb->pb_flags |= flags & (PBF_DELWRI | PBF_ASYNC);
1139                 pagebuf_delwri_queue(pb, 1);
1140                 return status;
1141         }
1142
1143         pb->pb_flags &= ~(PBF_READ | PBF_WRITE | PBF_ASYNC | PBF_DELWRI | \
1144                         PBF_READ_AHEAD | _PBF_RUN_QUEUES);
1145         pb->pb_flags |= flags & (PBF_READ | PBF_WRITE | PBF_ASYNC | \
1146                         PBF_READ_AHEAD | _PBF_RUN_QUEUES);
1147
1148         BUG_ON(pb->pb_bn == XFS_BUF_DADDR_NULL);
1149
1150         /* For writes allow an alternate strategy routine to precede
1151          * the actual I/O request (which may not be issued at all in
1152          * a shutdown situation, for example).
1153          */
1154         status = (flags & PBF_WRITE) ?
1155                 pagebuf_iostrategy(pb) : pagebuf_iorequest(pb);
1156
1157         /* Wait for I/O if we are not an async request.
1158          * Note: async I/O request completion will release the buffer,
1159          * and that can already be done by this point.  So using the
1160          * buffer pointer from here on, after async I/O, is invalid.
1161          */
1162         if (!status && !(flags & PBF_ASYNC))
1163                 status = pagebuf_iowait(pb);
1164
1165         return status;
1166 }
1167
1168 /*
1169  * Helper routine for pagebuf_iorequest
1170  */
1171
1172 STATIC __inline__ int
1173 _pagebuf_iolocked(
1174         xfs_buf_t               *pb)
1175 {
1176         ASSERT(pb->pb_flags & (PBF_READ|PBF_WRITE));
1177         if (pb->pb_flags & PBF_READ)
1178                 return pb->pb_locked;
1179         return 0;
1180 }
1181
1182 STATIC __inline__ void
1183 _pagebuf_iodone(
1184         xfs_buf_t               *pb,
1185         int                     schedule)
1186 {
1187         if (atomic_dec_and_test(&pb->pb_io_remaining) == 1) {
1188                 pb->pb_locked = 0;
1189                 pagebuf_iodone(pb, schedule);
1190         }
1191 }
1192
1193 STATIC int
1194 bio_end_io_pagebuf(
1195         struct bio              *bio,
1196         unsigned int            bytes_done,
1197         int                     error)
1198 {
1199         xfs_buf_t               *pb = (xfs_buf_t *)bio->bi_private;
1200         unsigned int            blocksize = pb->pb_target->pbr_bsize;
1201         struct bio_vec          *bvec = bio->bi_io_vec + bio->bi_vcnt - 1;
1202
1203         if (bio->bi_size)
1204                 return 1;
1205
1206         if (!test_bit(BIO_UPTODATE, &bio->bi_flags))
1207                 pb->pb_error = EIO;
1208
1209         do {
1210                 struct page     *page = bvec->bv_page;
1211
1212                 if (unlikely(pb->pb_error)) {
1213                         if (pb->pb_flags & PBF_READ)
1214                                 ClearPageUptodate(page);
1215                         SetPageError(page);
1216                 } else if (blocksize == PAGE_CACHE_SIZE) {
1217                         SetPageUptodate(page);
1218                 } else if (!PagePrivate(page) &&
1219                                 (pb->pb_flags & _PBF_PAGE_CACHE)) {
1220                         set_page_region(page, bvec->bv_offset, bvec->bv_len);
1221                 }
1222
1223                 if (--bvec >= bio->bi_io_vec)
1224                         prefetchw(&bvec->bv_page->flags);
1225
1226                 if (_pagebuf_iolocked(pb)) {
1227                         unlock_page(page);
1228                 }
1229         } while (bvec >= bio->bi_io_vec);
1230
1231         _pagebuf_iodone(pb, 1);
1232         bio_put(bio);
1233         return 0;
1234 }
1235
1236 STATIC void
1237 _pagebuf_ioapply(
1238         xfs_buf_t               *pb)
1239 {
1240         int                     i, rw, map_i, total_nr_pages, nr_pages;
1241         struct bio              *bio;
1242         int                     offset = pb->pb_offset;
1243         int                     size = pb->pb_count_desired;
1244         sector_t                sector = pb->pb_bn;
1245         unsigned int            blocksize = pb->pb_target->pbr_bsize;
1246         int                     locking = _pagebuf_iolocked(pb);
1247
1248         total_nr_pages = pb->pb_page_count;
1249         map_i = 0;
1250
1251         if (pb->pb_flags & _PBF_RUN_QUEUES) {
1252                 pb->pb_flags &= ~_PBF_RUN_QUEUES;
1253                 rw = (pb->pb_flags & PBF_READ) ? READ_SYNC : WRITE_SYNC;
1254         } else {
1255                 rw = (pb->pb_flags & PBF_READ) ? READ : WRITE;
1256         }
1257
1258         if (pb->pb_flags & PBF_ORDERED) {
1259                 ASSERT(!(pb->pb_flags & PBF_READ));
1260                 rw = WRITE_BARRIER;
1261         }
1262
1263         /* Special code path for reading a sub page size pagebuf in --
1264          * we populate up the whole page, and hence the other metadata
1265          * in the same page.  This optimization is only valid when the
1266          * filesystem block size and the page size are equal.
1267          */
1268         if ((pb->pb_buffer_length < PAGE_CACHE_SIZE) &&
1269             (pb->pb_flags & PBF_READ) && locking &&
1270             (blocksize == PAGE_CACHE_SIZE)) {
1271                 bio = bio_alloc(GFP_NOIO, 1);
1272
1273                 bio->bi_bdev = pb->pb_target->pbr_bdev;
1274                 bio->bi_sector = sector - (offset >> BBSHIFT);
1275                 bio->bi_end_io = bio_end_io_pagebuf;
1276                 bio->bi_private = pb;
1277
1278                 bio_add_page(bio, pb->pb_pages[0], PAGE_CACHE_SIZE, 0);
1279                 size = 0;
1280
1281                 atomic_inc(&pb->pb_io_remaining);
1282
1283                 goto submit_io;
1284         }
1285
1286         /* Lock down the pages which we need to for the request */
1287         if (locking && (pb->pb_flags & PBF_WRITE) && (pb->pb_locked == 0)) {
1288                 for (i = 0; size; i++) {
1289                         int             nbytes = PAGE_CACHE_SIZE - offset;
1290                         struct page     *page = pb->pb_pages[i];
1291
1292                         if (nbytes > size)
1293                                 nbytes = size;
1294
1295                         lock_page(page);
1296
1297                         size -= nbytes;
1298                         offset = 0;
1299                 }
1300                 offset = pb->pb_offset;
1301                 size = pb->pb_count_desired;
1302         }
1303
1304 next_chunk:
1305         atomic_inc(&pb->pb_io_remaining);
1306         nr_pages = BIO_MAX_SECTORS >> (PAGE_SHIFT - BBSHIFT);
1307         if (nr_pages > total_nr_pages)
1308                 nr_pages = total_nr_pages;
1309
1310         bio = bio_alloc(GFP_NOIO, nr_pages);
1311         bio->bi_bdev = pb->pb_target->pbr_bdev;
1312         bio->bi_sector = sector;
1313         bio->bi_end_io = bio_end_io_pagebuf;
1314         bio->bi_private = pb;
1315
1316         for (; size && nr_pages; nr_pages--, map_i++) {
1317                 int     nbytes = PAGE_CACHE_SIZE - offset;
1318
1319                 if (nbytes > size)
1320                         nbytes = size;
1321
1322                 if (bio_add_page(bio, pb->pb_pages[map_i],
1323                                         nbytes, offset) < nbytes)
1324                         break;
1325
1326                 offset = 0;
1327                 sector += nbytes >> BBSHIFT;
1328                 size -= nbytes;
1329                 total_nr_pages--;
1330         }
1331
1332 submit_io:
1333         if (likely(bio->bi_size)) {
1334                 submit_bio(rw, bio);
1335                 if (size)
1336                         goto next_chunk;
1337         } else {
1338                 bio_put(bio);
1339                 pagebuf_ioerror(pb, EIO);
1340         }
1341 }
1342
1343 /*
1344  *      pagebuf_iorequest -- the core I/O request routine.
1345  */
1346 int
1347 pagebuf_iorequest(                      /* start real I/O               */
1348         xfs_buf_t               *pb)    /* buffer to convey to device   */
1349 {
1350         PB_TRACE(pb, "iorequest", 0);
1351
1352         if (pb->pb_flags & PBF_DELWRI) {
1353                 pagebuf_delwri_queue(pb, 1);
1354                 return 0;
1355         }
1356
1357         if (pb->pb_flags & PBF_WRITE) {
1358                 _pagebuf_wait_unpin(pb);
1359         }
1360
1361         pagebuf_hold(pb);
1362
1363         /* Set the count to 1 initially, this will stop an I/O
1364          * completion callout which happens before we have started
1365          * all the I/O from calling pagebuf_iodone too early.
1366          */
1367         atomic_set(&pb->pb_io_remaining, 1);
1368         _pagebuf_ioapply(pb);
1369         _pagebuf_iodone(pb, 0);
1370
1371         pagebuf_rele(pb);
1372         return 0;
1373 }
1374
1375 /*
1376  *      pagebuf_iowait
1377  *
1378  *      pagebuf_iowait waits for I/O to complete on the buffer supplied.
1379  *      It returns immediately if no I/O is pending.  In any case, it returns
1380  *      the error code, if any, or 0 if there is no error.
1381  */
1382 int
1383 pagebuf_iowait(
1384         xfs_buf_t               *pb)
1385 {
1386         PB_TRACE(pb, "iowait", 0);
1387         if (atomic_read(&pb->pb_io_remaining))
1388                 blk_run_address_space(pb->pb_target->pbr_mapping);
1389         down(&pb->pb_iodonesema);
1390         PB_TRACE(pb, "iowaited", (long)pb->pb_error);
1391         return pb->pb_error;
1392 }
1393
1394 caddr_t
1395 pagebuf_offset(
1396         xfs_buf_t               *pb,
1397         size_t                  offset)
1398 {
1399         struct page             *page;
1400
1401         offset += pb->pb_offset;
1402
1403         page = pb->pb_pages[offset >> PAGE_CACHE_SHIFT];
1404         return (caddr_t) page_address(page) + (offset & (PAGE_CACHE_SIZE - 1));
1405 }
1406
1407 /*
1408  *      pagebuf_iomove
1409  *
1410  *      Move data into or out of a buffer.
1411  */
1412 void
1413 pagebuf_iomove(
1414         xfs_buf_t               *pb,    /* buffer to process            */
1415         size_t                  boff,   /* starting buffer offset       */
1416         size_t                  bsize,  /* length to copy               */
1417         caddr_t                 data,   /* data address                 */
1418         page_buf_rw_t           mode)   /* read/write flag              */
1419 {
1420         size_t                  bend, cpoff, csize;
1421         struct page             *page;
1422
1423         bend = boff + bsize;
1424         while (boff < bend) {
1425                 page = pb->pb_pages[page_buf_btoct(boff + pb->pb_offset)];
1426                 cpoff = page_buf_poff(boff + pb->pb_offset);
1427                 csize = min_t(size_t,
1428                               PAGE_CACHE_SIZE-cpoff, pb->pb_count_desired-boff);
1429
1430                 ASSERT(((csize + cpoff) <= PAGE_CACHE_SIZE));
1431
1432                 switch (mode) {
1433                 case PBRW_ZERO:
1434                         memset(page_address(page) + cpoff, 0, csize);
1435                         break;
1436                 case PBRW_READ:
1437                         memcpy(data, page_address(page) + cpoff, csize);
1438                         break;
1439                 case PBRW_WRITE:
1440                         memcpy(page_address(page) + cpoff, data, csize);
1441                 }
1442
1443                 boff += csize;
1444                 data += csize;
1445         }
1446 }
1447
1448 /*
1449  *      Handling of buftargs.
1450  */
1451
1452 /*
1453  * Wait for any bufs with callbacks that have been submitted but
1454  * have not yet returned... walk the hash list for the target.
1455  */
1456 void
1457 xfs_wait_buftarg(
1458         xfs_buftarg_t   *btp)
1459 {
1460         xfs_buf_t       *bp, *n;
1461         xfs_bufhash_t   *hash;
1462         uint            i;
1463
1464         for (i = 0; i < (1 << btp->bt_hashshift); i++) {
1465                 hash = &btp->bt_hash[i];
1466 again:
1467                 spin_lock(&hash->bh_lock);
1468                 list_for_each_entry_safe(bp, n, &hash->bh_list, pb_hash_list) {
1469                         ASSERT(btp == bp->pb_target);
1470                         if (!(bp->pb_flags & PBF_FS_MANAGED)) {
1471                                 spin_unlock(&hash->bh_lock);
1472                                 /*
1473                                  * Catch superblock reference count leaks
1474                                  * immediately
1475                                  */
1476                                 BUG_ON(bp->pb_bn == 0);
1477                                 delay(100);
1478                                 goto again;
1479                         }
1480                 }
1481                 spin_unlock(&hash->bh_lock);
1482         }
1483 }
1484
1485 /*
1486  * Allocate buffer hash table for a given target.
1487  * For devices containing metadata (i.e. not the log/realtime devices)
1488  * we need to allocate a much larger hash table.
1489  */
1490 STATIC void
1491 xfs_alloc_bufhash(
1492         xfs_buftarg_t           *btp,
1493         int                     external)
1494 {
1495         unsigned int            i;
1496
1497         btp->bt_hashshift = external ? 3 : 8;   /* 8 or 256 buckets */
1498         btp->bt_hashmask = (1 << btp->bt_hashshift) - 1;
1499         btp->bt_hash = kmem_zalloc((1 << btp->bt_hashshift) *
1500                                         sizeof(xfs_bufhash_t), KM_SLEEP);
1501         for (i = 0; i < (1 << btp->bt_hashshift); i++) {
1502                 spin_lock_init(&btp->bt_hash[i].bh_lock);
1503                 INIT_LIST_HEAD(&btp->bt_hash[i].bh_list);
1504         }
1505 }
1506
1507 STATIC void
1508 xfs_free_bufhash(
1509         xfs_buftarg_t           *btp)
1510 {
1511         kmem_free(btp->bt_hash,
1512                         (1 << btp->bt_hashshift) * sizeof(xfs_bufhash_t));
1513         btp->bt_hash = NULL;
1514 }
1515
1516 void
1517 xfs_free_buftarg(
1518         xfs_buftarg_t           *btp,
1519         int                     external)
1520 {
1521         xfs_flush_buftarg(btp, 1);
1522         if (external)
1523                 xfs_blkdev_put(btp->pbr_bdev);
1524         xfs_free_bufhash(btp);
1525         iput(btp->pbr_mapping->host);
1526         kmem_free(btp, sizeof(*btp));
1527 }
1528
1529 STATIC int
1530 xfs_setsize_buftarg_flags(
1531         xfs_buftarg_t           *btp,
1532         unsigned int            blocksize,
1533         unsigned int            sectorsize,
1534         int                     verbose)
1535 {
1536         btp->pbr_bsize = blocksize;
1537         btp->pbr_sshift = ffs(sectorsize) - 1;
1538         btp->pbr_smask = sectorsize - 1;
1539
1540         if (set_blocksize(btp->pbr_bdev, sectorsize)) {
1541                 printk(KERN_WARNING
1542                         "XFS: Cannot set_blocksize to %u on device %s\n",
1543                         sectorsize, XFS_BUFTARG_NAME(btp));
1544                 return EINVAL;
1545         }
1546
1547         if (verbose &&
1548             (PAGE_CACHE_SIZE / BITS_PER_LONG) > sectorsize) {
1549                 printk(KERN_WARNING
1550                         "XFS: %u byte sectors in use on device %s.  "
1551                         "This is suboptimal; %u or greater is ideal.\n",
1552                         sectorsize, XFS_BUFTARG_NAME(btp),
1553                         (unsigned int)PAGE_CACHE_SIZE / BITS_PER_LONG);
1554         }
1555
1556         return 0;
1557 }
1558
1559 /*
1560 * When allocating the initial buffer target we have not yet
1561 * read in the superblock, so don't know what sized sectors
1562 * are being used is at this early stage.  Play safe.
1563 */
1564 STATIC int
1565 xfs_setsize_buftarg_early(
1566         xfs_buftarg_t           *btp,
1567         struct block_device     *bdev)
1568 {
1569         return xfs_setsize_buftarg_flags(btp,
1570                         PAGE_CACHE_SIZE, bdev_hardsect_size(bdev), 0);
1571 }
1572
1573 int
1574 xfs_setsize_buftarg(
1575         xfs_buftarg_t           *btp,
1576         unsigned int            blocksize,
1577         unsigned int            sectorsize)
1578 {
1579         return xfs_setsize_buftarg_flags(btp, blocksize, sectorsize, 1);
1580 }
1581
1582 STATIC int
1583 xfs_mapping_buftarg(
1584         xfs_buftarg_t           *btp,
1585         struct block_device     *bdev)
1586 {
1587         struct backing_dev_info *bdi;
1588         struct inode            *inode;
1589         struct address_space    *mapping;
1590         static struct address_space_operations mapping_aops = {
1591                 .sync_page = block_sync_page,
1592         };
1593
1594         inode = new_inode(bdev->bd_inode->i_sb);
1595         if (!inode) {
1596                 printk(KERN_WARNING
1597                         "XFS: Cannot allocate mapping inode for device %s\n",
1598                         XFS_BUFTARG_NAME(btp));
1599                 return ENOMEM;
1600         }
1601         inode->i_mode = S_IFBLK;
1602         inode->i_bdev = bdev;
1603         inode->i_rdev = bdev->bd_dev;
1604         bdi = blk_get_backing_dev_info(bdev);
1605         if (!bdi)
1606                 bdi = &default_backing_dev_info;
1607         mapping = &inode->i_data;
1608         mapping->a_ops = &mapping_aops;
1609         mapping->backing_dev_info = bdi;
1610         mapping_set_gfp_mask(mapping, GFP_NOFS);
1611         btp->pbr_mapping = mapping;
1612         return 0;
1613 }
1614
1615 xfs_buftarg_t *
1616 xfs_alloc_buftarg(
1617         struct block_device     *bdev,
1618         int                     external)
1619 {
1620         xfs_buftarg_t           *btp;
1621
1622         btp = kmem_zalloc(sizeof(*btp), KM_SLEEP);
1623
1624         btp->pbr_dev =  bdev->bd_dev;
1625         btp->pbr_bdev = bdev;
1626         if (xfs_setsize_buftarg_early(btp, bdev))
1627                 goto error;
1628         if (xfs_mapping_buftarg(btp, bdev))
1629                 goto error;
1630         xfs_alloc_bufhash(btp, external);
1631         return btp;
1632
1633 error:
1634         kmem_free(btp, sizeof(*btp));
1635         return NULL;
1636 }
1637
1638
1639 /*
1640  * Pagebuf delayed write buffer handling
1641  */
1642
1643 STATIC LIST_HEAD(pbd_delwrite_queue);
1644 STATIC DEFINE_SPINLOCK(pbd_delwrite_lock);
1645
1646 STATIC void
1647 pagebuf_delwri_queue(
1648         xfs_buf_t               *pb,
1649         int                     unlock)
1650 {
1651         PB_TRACE(pb, "delwri_q", (long)unlock);
1652         ASSERT((pb->pb_flags & (PBF_DELWRI|PBF_ASYNC)) ==
1653                                         (PBF_DELWRI|PBF_ASYNC));
1654
1655         spin_lock(&pbd_delwrite_lock);
1656         /* If already in the queue, dequeue and place at tail */
1657         if (!list_empty(&pb->pb_list)) {
1658                 ASSERT(pb->pb_flags & _PBF_DELWRI_Q);
1659                 if (unlock) {
1660                         atomic_dec(&pb->pb_hold);
1661                 }
1662                 list_del(&pb->pb_list);
1663         }
1664
1665         pb->pb_flags |= _PBF_DELWRI_Q;
1666         list_add_tail(&pb->pb_list, &pbd_delwrite_queue);
1667         pb->pb_queuetime = jiffies;
1668         spin_unlock(&pbd_delwrite_lock);
1669
1670         if (unlock)
1671                 pagebuf_unlock(pb);
1672 }
1673
1674 void
1675 pagebuf_delwri_dequeue(
1676         xfs_buf_t               *pb)
1677 {
1678         int                     dequeued = 0;
1679
1680         spin_lock(&pbd_delwrite_lock);
1681         if ((pb->pb_flags & PBF_DELWRI) && !list_empty(&pb->pb_list)) {
1682                 ASSERT(pb->pb_flags & _PBF_DELWRI_Q);
1683                 list_del_init(&pb->pb_list);
1684                 dequeued = 1;
1685         }
1686         pb->pb_flags &= ~(PBF_DELWRI|_PBF_DELWRI_Q);
1687         spin_unlock(&pbd_delwrite_lock);
1688
1689         if (dequeued)
1690                 pagebuf_rele(pb);
1691
1692         PB_TRACE(pb, "delwri_dq", (long)dequeued);
1693 }
1694
1695 STATIC void
1696 pagebuf_runall_queues(
1697         struct workqueue_struct *queue)
1698 {
1699         flush_workqueue(queue);
1700 }
1701
1702 /* Defines for pagebuf daemon */
1703 STATIC struct task_struct *xfsbufd_task;
1704 STATIC int xfsbufd_force_flush;
1705 STATIC int xfsbufd_force_sleep;
1706
1707 STATIC int
1708 xfsbufd_wakeup(
1709         int             priority,
1710         gfp_t           mask)
1711 {
1712         if (xfsbufd_force_sleep)
1713                 return 0;
1714         xfsbufd_force_flush = 1;
1715         barrier();
1716         wake_up_process(xfsbufd_task);
1717         return 0;
1718 }
1719
1720 STATIC int
1721 xfsbufd(
1722         void                    *data)
1723 {
1724         struct list_head        tmp;
1725         unsigned long           age;
1726         xfs_buftarg_t           *target;
1727         xfs_buf_t               *pb, *n;
1728
1729         current->flags |= PF_MEMALLOC;
1730
1731         INIT_LIST_HEAD(&tmp);
1732         do {
1733                 if (unlikely(freezing(current))) {
1734                         xfsbufd_force_sleep = 1;
1735                         refrigerator();
1736                 } else {
1737                         xfsbufd_force_sleep = 0;
1738                 }
1739
1740                 schedule_timeout_interruptible
1741                         (xfs_buf_timer_centisecs * msecs_to_jiffies(10));
1742
1743                 age = xfs_buf_age_centisecs * msecs_to_jiffies(10);
1744                 spin_lock(&pbd_delwrite_lock);
1745                 list_for_each_entry_safe(pb, n, &pbd_delwrite_queue, pb_list) {
1746                         PB_TRACE(pb, "walkq1", (long)pagebuf_ispin(pb));
1747                         ASSERT(pb->pb_flags & PBF_DELWRI);
1748
1749                         if (!pagebuf_ispin(pb) && !pagebuf_cond_lock(pb)) {
1750                                 if (!xfsbufd_force_flush &&
1751                                     time_before(jiffies,
1752                                                 pb->pb_queuetime + age)) {
1753                                         pagebuf_unlock(pb);
1754                                         break;
1755                                 }
1756
1757                                 pb->pb_flags &= ~(PBF_DELWRI|_PBF_DELWRI_Q);
1758                                 pb->pb_flags |= PBF_WRITE;
1759                                 list_move(&pb->pb_list, &tmp);
1760                         }
1761                 }
1762                 spin_unlock(&pbd_delwrite_lock);
1763
1764                 while (!list_empty(&tmp)) {
1765                         pb = list_entry(tmp.next, xfs_buf_t, pb_list);
1766                         target = pb->pb_target;
1767
1768                         list_del_init(&pb->pb_list);
1769                         pagebuf_iostrategy(pb);
1770
1771                         blk_run_address_space(target->pbr_mapping);
1772                 }
1773
1774                 if (as_list_len > 0)
1775                         purge_addresses();
1776
1777                 xfsbufd_force_flush = 0;
1778         } while (!kthread_should_stop());
1779
1780         return 0;
1781 }
1782
1783 /*
1784  * Go through all incore buffers, and release buffers if they belong to
1785  * the given device. This is used in filesystem error handling to
1786  * preserve the consistency of its metadata.
1787  */
1788 int
1789 xfs_flush_buftarg(
1790         xfs_buftarg_t           *target,
1791         int                     wait)
1792 {
1793         struct list_head        tmp;
1794         xfs_buf_t               *pb, *n;
1795         int                     pincount = 0;
1796
1797         pagebuf_runall_queues(xfsdatad_workqueue);
1798         pagebuf_runall_queues(xfslogd_workqueue);
1799
1800         INIT_LIST_HEAD(&tmp);
1801         spin_lock(&pbd_delwrite_lock);
1802         list_for_each_entry_safe(pb, n, &pbd_delwrite_queue, pb_list) {
1803
1804                 if (pb->pb_target != target)
1805                         continue;
1806
1807                 ASSERT(pb->pb_flags & (PBF_DELWRI|_PBF_DELWRI_Q));
1808                 PB_TRACE(pb, "walkq2", (long)pagebuf_ispin(pb));
1809                 if (pagebuf_ispin(pb)) {
1810                         pincount++;
1811                         continue;
1812                 }
1813
1814                 list_move(&pb->pb_list, &tmp);
1815         }
1816         spin_unlock(&pbd_delwrite_lock);
1817
1818         /*
1819          * Dropped the delayed write list lock, now walk the temporary list
1820          */
1821         list_for_each_entry_safe(pb, n, &tmp, pb_list) {
1822                 pagebuf_lock(pb);
1823                 pb->pb_flags &= ~(PBF_DELWRI|_PBF_DELWRI_Q);
1824                 pb->pb_flags |= PBF_WRITE;
1825                 if (wait)
1826                         pb->pb_flags &= ~PBF_ASYNC;
1827                 else
1828                         list_del_init(&pb->pb_list);
1829
1830                 pagebuf_iostrategy(pb);
1831         }
1832
1833         /*
1834          * Remaining list items must be flushed before returning
1835          */
1836         while (!list_empty(&tmp)) {
1837                 pb = list_entry(tmp.next, xfs_buf_t, pb_list);
1838
1839                 list_del_init(&pb->pb_list);
1840                 xfs_iowait(pb);
1841                 xfs_buf_relse(pb);
1842         }
1843
1844         if (wait)
1845                 blk_run_address_space(target->pbr_mapping);
1846
1847         return pincount;
1848 }
1849
1850 int __init
1851 pagebuf_init(void)
1852 {
1853         int             error = -ENOMEM;
1854
1855 #ifdef PAGEBUF_TRACE
1856         pagebuf_trace_buf = ktrace_alloc(PAGEBUF_TRACE_SIZE, KM_SLEEP);
1857 #endif
1858
1859         pagebuf_zone = kmem_zone_init(sizeof(xfs_buf_t), "xfs_buf");
1860         if (!pagebuf_zone)
1861                 goto out_free_trace_buf;
1862
1863         xfslogd_workqueue = create_workqueue("xfslogd");
1864         if (!xfslogd_workqueue)
1865                 goto out_free_buf_zone;
1866
1867         xfsdatad_workqueue = create_workqueue("xfsdatad");
1868         if (!xfsdatad_workqueue)
1869                 goto out_destroy_xfslogd_workqueue;
1870
1871         xfsbufd_task = kthread_run(xfsbufd, NULL, "xfsbufd");
1872         if (IS_ERR(xfsbufd_task)) {
1873                 error = PTR_ERR(xfsbufd_task);
1874                 goto out_destroy_xfsdatad_workqueue;
1875         }
1876
1877         pagebuf_shake = kmem_shake_register(xfsbufd_wakeup);
1878         if (!pagebuf_shake)
1879                 goto out_stop_xfsbufd;
1880
1881         return 0;
1882
1883  out_stop_xfsbufd:
1884         kthread_stop(xfsbufd_task);
1885  out_destroy_xfsdatad_workqueue:
1886         destroy_workqueue(xfsdatad_workqueue);
1887  out_destroy_xfslogd_workqueue:
1888         destroy_workqueue(xfslogd_workqueue);
1889  out_free_buf_zone:
1890         kmem_zone_destroy(pagebuf_zone);
1891  out_free_trace_buf:
1892 #ifdef PAGEBUF_TRACE
1893         ktrace_free(pagebuf_trace_buf);
1894 #endif
1895         return error;
1896 }
1897
1898 void
1899 pagebuf_terminate(void)
1900 {
1901         kmem_shake_deregister(pagebuf_shake);
1902         kthread_stop(xfsbufd_task);
1903         destroy_workqueue(xfsdatad_workqueue);
1904         destroy_workqueue(xfslogd_workqueue);
1905         kmem_zone_destroy(pagebuf_zone);
1906 #ifdef PAGEBUF_TRACE
1907         ktrace_free(pagebuf_trace_buf);
1908 #endif
1909 }