xref: /openbmc/linux/fs/gfs2/bmap.c (revision b627b4ed)
1 /*
2  * Copyright (C) Sistina Software, Inc.  1997-2003 All rights reserved.
3  * Copyright (C) 2004-2006 Red Hat, Inc.  All rights reserved.
4  *
5  * This copyrighted material is made available to anyone wishing to use,
6  * modify, copy, or redistribute it subject to the terms and conditions
7  * of the GNU General Public License version 2.
8  */
9 
10 #include <linux/slab.h>
11 #include <linux/spinlock.h>
12 #include <linux/completion.h>
13 #include <linux/buffer_head.h>
14 #include <linux/gfs2_ondisk.h>
15 #include <linux/crc32.h>
16 
17 #include "gfs2.h"
18 #include "incore.h"
19 #include "bmap.h"
20 #include "glock.h"
21 #include "inode.h"
22 #include "meta_io.h"
23 #include "quota.h"
24 #include "rgrp.h"
25 #include "trans.h"
26 #include "dir.h"
27 #include "util.h"
28 #include "ops_address.h"
29 
30 /* This doesn't need to be that large as max 64 bit pointers in a 4k
31  * block is 512, so __u16 is fine for that. It saves stack space to
32  * keep it small.
33  */
34 struct metapath {
35 	struct buffer_head *mp_bh[GFS2_MAX_META_HEIGHT];
36 	__u16 mp_list[GFS2_MAX_META_HEIGHT];
37 };
38 
39 typedef int (*block_call_t) (struct gfs2_inode *ip, struct buffer_head *dibh,
40 			     struct buffer_head *bh, __be64 *top,
41 			     __be64 *bottom, unsigned int height,
42 			     void *data);
43 
44 struct strip_mine {
45 	int sm_first;
46 	unsigned int sm_height;
47 };
48 
49 /**
50  * gfs2_unstuffer_page - unstuff a stuffed inode into a block cached by a page
51  * @ip: the inode
52  * @dibh: the dinode buffer
53  * @block: the block number that was allocated
54  * @private: any locked page held by the caller process
55  *
56  * Returns: errno
57  */
58 
59 static int gfs2_unstuffer_page(struct gfs2_inode *ip, struct buffer_head *dibh,
60 			       u64 block, struct page *page)
61 {
62 	struct inode *inode = &ip->i_inode;
63 	struct buffer_head *bh;
64 	int release = 0;
65 
66 	if (!page || page->index) {
67 		page = grab_cache_page(inode->i_mapping, 0);
68 		if (!page)
69 			return -ENOMEM;
70 		release = 1;
71 	}
72 
73 	if (!PageUptodate(page)) {
74 		void *kaddr = kmap(page);
75 
76 		memcpy(kaddr, dibh->b_data + sizeof(struct gfs2_dinode),
77 		       ip->i_disksize);
78 		memset(kaddr + ip->i_disksize, 0,
79 		       PAGE_CACHE_SIZE - ip->i_disksize);
80 		kunmap(page);
81 
82 		SetPageUptodate(page);
83 	}
84 
85 	if (!page_has_buffers(page))
86 		create_empty_buffers(page, 1 << inode->i_blkbits,
87 				     (1 << BH_Uptodate));
88 
89 	bh = page_buffers(page);
90 
91 	if (!buffer_mapped(bh))
92 		map_bh(bh, inode->i_sb, block);
93 
94 	set_buffer_uptodate(bh);
95 	if (!gfs2_is_jdata(ip))
96 		mark_buffer_dirty(bh);
97 	if (!gfs2_is_writeback(ip))
98 		gfs2_trans_add_bh(ip->i_gl, bh, 0);
99 
100 	if (release) {
101 		unlock_page(page);
102 		page_cache_release(page);
103 	}
104 
105 	return 0;
106 }
107 
108 /**
109  * gfs2_unstuff_dinode - Unstuff a dinode when the data has grown too big
110  * @ip: The GFS2 inode to unstuff
111  * @unstuffer: the routine that handles unstuffing a non-zero length file
112  * @private: private data for the unstuffer
113  *
114  * This routine unstuffs a dinode and returns it to a "normal" state such
115  * that the height can be grown in the traditional way.
116  *
117  * Returns: errno
118  */
119 
120 int gfs2_unstuff_dinode(struct gfs2_inode *ip, struct page *page)
121 {
122 	struct buffer_head *bh, *dibh;
123 	struct gfs2_dinode *di;
124 	u64 block = 0;
125 	int isdir = gfs2_is_dir(ip);
126 	int error;
127 
128 	down_write(&ip->i_rw_mutex);
129 
130 	error = gfs2_meta_inode_buffer(ip, &dibh);
131 	if (error)
132 		goto out;
133 
134 	if (ip->i_disksize) {
135 		/* Get a free block, fill it with the stuffed data,
136 		   and write it out to disk */
137 
138 		unsigned int n = 1;
139 		block = gfs2_alloc_block(ip, &n);
140 		if (isdir) {
141 			gfs2_trans_add_unrevoke(GFS2_SB(&ip->i_inode), block, 1);
142 			error = gfs2_dir_get_new_buffer(ip, block, &bh);
143 			if (error)
144 				goto out_brelse;
145 			gfs2_buffer_copy_tail(bh, sizeof(struct gfs2_meta_header),
146 					      dibh, sizeof(struct gfs2_dinode));
147 			brelse(bh);
148 		} else {
149 			error = gfs2_unstuffer_page(ip, dibh, block, page);
150 			if (error)
151 				goto out_brelse;
152 		}
153 	}
154 
155 	/*  Set up the pointer to the new block  */
156 
157 	gfs2_trans_add_bh(ip->i_gl, dibh, 1);
158 	di = (struct gfs2_dinode *)dibh->b_data;
159 	gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
160 
161 	if (ip->i_disksize) {
162 		*(__be64 *)(di + 1) = cpu_to_be64(block);
163 		gfs2_add_inode_blocks(&ip->i_inode, 1);
164 		di->di_blocks = cpu_to_be64(gfs2_get_inode_blocks(&ip->i_inode));
165 	}
166 
167 	ip->i_height = 1;
168 	di->di_height = cpu_to_be16(1);
169 
170 out_brelse:
171 	brelse(dibh);
172 out:
173 	up_write(&ip->i_rw_mutex);
174 	return error;
175 }
176 
177 
178 /**
179  * find_metapath - Find path through the metadata tree
180  * @sdp: The superblock
181  * @mp: The metapath to return the result in
182  * @block: The disk block to look up
183  * @height: The pre-calculated height of the metadata tree
184  *
185  *   This routine returns a struct metapath structure that defines a path
186  *   through the metadata of inode "ip" to get to block "block".
187  *
188  *   Example:
189  *   Given:  "ip" is a height 3 file, "offset" is 101342453, and this is a
190  *   filesystem with a blocksize of 4096.
191  *
192  *   find_metapath() would return a struct metapath structure set to:
193  *   mp_offset = 101342453, mp_height = 3, mp_list[0] = 0, mp_list[1] = 48,
194  *   and mp_list[2] = 165.
195  *
196  *   That means that in order to get to the block containing the byte at
197  *   offset 101342453, we would load the indirect block pointed to by pointer
198  *   0 in the dinode.  We would then load the indirect block pointed to by
199  *   pointer 48 in that indirect block.  We would then load the data block
200  *   pointed to by pointer 165 in that indirect block.
201  *
202  *             ----------------------------------------
203  *             | Dinode |                             |
204  *             |        |                            4|
205  *             |        |0 1 2 3 4 5                 9|
206  *             |        |                            6|
207  *             ----------------------------------------
208  *                       |
209  *                       |
210  *                       V
211  *             ----------------------------------------
212  *             | Indirect Block                       |
213  *             |                                     5|
214  *             |            4 4 4 4 4 5 5            1|
215  *             |0           5 6 7 8 9 0 1            2|
216  *             ----------------------------------------
217  *                                |
218  *                                |
219  *                                V
220  *             ----------------------------------------
221  *             | Indirect Block                       |
222  *             |                         1 1 1 1 1   5|
223  *             |                         6 6 6 6 6   1|
224  *             |0                        3 4 5 6 7   2|
225  *             ----------------------------------------
226  *                                           |
227  *                                           |
228  *                                           V
229  *             ----------------------------------------
230  *             | Data block containing offset         |
231  *             |            101342453                 |
232  *             |                                      |
233  *             |                                      |
234  *             ----------------------------------------
235  *
236  */
237 
238 static void find_metapath(const struct gfs2_sbd *sdp, u64 block,
239 			  struct metapath *mp, unsigned int height)
240 {
241 	unsigned int i;
242 
243 	for (i = height; i--;)
244 		mp->mp_list[i] = do_div(block, sdp->sd_inptrs);
245 
246 }
247 
248 static inline unsigned int metapath_branch_start(const struct metapath *mp)
249 {
250 	if (mp->mp_list[0] == 0)
251 		return 2;
252 	return 1;
253 }
254 
255 /**
256  * metapointer - Return pointer to start of metadata in a buffer
257  * @height: The metadata height (0 = dinode)
258  * @mp: The metapath
259  *
260  * Return a pointer to the block number of the next height of the metadata
261  * tree given a buffer containing the pointer to the current height of the
262  * metadata tree.
263  */
264 
265 static inline __be64 *metapointer(unsigned int height, const struct metapath *mp)
266 {
267 	struct buffer_head *bh = mp->mp_bh[height];
268 	unsigned int head_size = (height > 0) ?
269 		sizeof(struct gfs2_meta_header) : sizeof(struct gfs2_dinode);
270 	return ((__be64 *)(bh->b_data + head_size)) + mp->mp_list[height];
271 }
272 
273 /**
274  * lookup_metapath - Walk the metadata tree to a specific point
275  * @ip: The inode
276  * @mp: The metapath
277  *
278  * Assumes that the inode's buffer has already been looked up and
279  * hooked onto mp->mp_bh[0] and that the metapath has been initialised
280  * by find_metapath().
281  *
282  * If this function encounters part of the tree which has not been
283  * allocated, it returns the current height of the tree at the point
284  * at which it found the unallocated block. Blocks which are found are
285  * added to the mp->mp_bh[] list.
286  *
287  * Returns: error or height of metadata tree
288  */
289 
290 static int lookup_metapath(struct gfs2_inode *ip, struct metapath *mp)
291 {
292 	unsigned int end_of_metadata = ip->i_height - 1;
293 	unsigned int x;
294 	__be64 *ptr;
295 	u64 dblock;
296 	int ret;
297 
298 	for (x = 0; x < end_of_metadata; x++) {
299 		ptr = metapointer(x, mp);
300 		dblock = be64_to_cpu(*ptr);
301 		if (!dblock)
302 			return x + 1;
303 
304 		ret = gfs2_meta_indirect_buffer(ip, x+1, dblock, 0, &mp->mp_bh[x+1]);
305 		if (ret)
306 			return ret;
307 	}
308 
309 	return ip->i_height;
310 }
311 
312 static inline void release_metapath(struct metapath *mp)
313 {
314 	int i;
315 
316 	for (i = 0; i < GFS2_MAX_META_HEIGHT; i++) {
317 		if (mp->mp_bh[i] == NULL)
318 			break;
319 		brelse(mp->mp_bh[i]);
320 	}
321 }
322 
323 /**
324  * gfs2_extent_length - Returns length of an extent of blocks
325  * @start: Start of the buffer
326  * @len: Length of the buffer in bytes
327  * @ptr: Current position in the buffer
328  * @limit: Max extent length to return (0 = unlimited)
329  * @eob: Set to 1 if we hit "end of block"
330  *
331  * If the first block is zero (unallocated) it will return the number of
332  * unallocated blocks in the extent, otherwise it will return the number
333  * of contiguous blocks in the extent.
334  *
335  * Returns: The length of the extent (minimum of one block)
336  */
337 
338 static inline unsigned int gfs2_extent_length(void *start, unsigned int len, __be64 *ptr, unsigned limit, int *eob)
339 {
340 	const __be64 *end = (start + len);
341 	const __be64 *first = ptr;
342 	u64 d = be64_to_cpu(*ptr);
343 
344 	*eob = 0;
345 	do {
346 		ptr++;
347 		if (ptr >= end)
348 			break;
349 		if (limit && --limit == 0)
350 			break;
351 		if (d)
352 			d++;
353 	} while(be64_to_cpu(*ptr) == d);
354 	if (ptr >= end)
355 		*eob = 1;
356 	return (ptr - first);
357 }
358 
359 static inline void bmap_lock(struct gfs2_inode *ip, int create)
360 {
361 	if (create)
362 		down_write(&ip->i_rw_mutex);
363 	else
364 		down_read(&ip->i_rw_mutex);
365 }
366 
367 static inline void bmap_unlock(struct gfs2_inode *ip, int create)
368 {
369 	if (create)
370 		up_write(&ip->i_rw_mutex);
371 	else
372 		up_read(&ip->i_rw_mutex);
373 }
374 
375 static inline __be64 *gfs2_indirect_init(struct metapath *mp,
376 					 struct gfs2_glock *gl, unsigned int i,
377 					 unsigned offset, u64 bn)
378 {
379 	__be64 *ptr = (__be64 *)(mp->mp_bh[i - 1]->b_data +
380 		       ((i > 1) ? sizeof(struct gfs2_meta_header) :
381 				 sizeof(struct gfs2_dinode)));
382 	BUG_ON(i < 1);
383 	BUG_ON(mp->mp_bh[i] != NULL);
384 	mp->mp_bh[i] = gfs2_meta_new(gl, bn);
385 	gfs2_trans_add_bh(gl, mp->mp_bh[i], 1);
386 	gfs2_metatype_set(mp->mp_bh[i], GFS2_METATYPE_IN, GFS2_FORMAT_IN);
387 	gfs2_buffer_clear_tail(mp->mp_bh[i], sizeof(struct gfs2_meta_header));
388 	ptr += offset;
389 	*ptr = cpu_to_be64(bn);
390 	return ptr;
391 }
392 
393 enum alloc_state {
394 	ALLOC_DATA = 0,
395 	ALLOC_GROW_DEPTH = 1,
396 	ALLOC_GROW_HEIGHT = 2,
397 	/* ALLOC_UNSTUFF = 3,   TBD and rather complicated */
398 };
399 
400 /**
401  * gfs2_bmap_alloc - Build a metadata tree of the requested height
402  * @inode: The GFS2 inode
403  * @lblock: The logical starting block of the extent
404  * @bh_map: This is used to return the mapping details
405  * @mp: The metapath
406  * @sheight: The starting height (i.e. whats already mapped)
407  * @height: The height to build to
408  * @maxlen: The max number of data blocks to alloc
409  *
410  * In this routine we may have to alloc:
411  *   i) Indirect blocks to grow the metadata tree height
412  *  ii) Indirect blocks to fill in lower part of the metadata tree
413  * iii) Data blocks
414  *
415  * The function is in two parts. The first part works out the total
416  * number of blocks which we need. The second part does the actual
417  * allocation asking for an extent at a time (if enough contiguous free
418  * blocks are available, there will only be one request per bmap call)
419  * and uses the state machine to initialise the blocks in order.
420  *
421  * Returns: errno on error
422  */
423 
424 static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock,
425 			   struct buffer_head *bh_map, struct metapath *mp,
426 			   const unsigned int sheight,
427 			   const unsigned int height,
428 			   const unsigned int maxlen)
429 {
430 	struct gfs2_inode *ip = GFS2_I(inode);
431 	struct gfs2_sbd *sdp = GFS2_SB(inode);
432 	struct buffer_head *dibh = mp->mp_bh[0];
433 	u64 bn, dblock = 0;
434 	unsigned n, i, blks, alloced = 0, iblks = 0, branch_start = 0;
435 	unsigned dblks = 0;
436 	unsigned ptrs_per_blk;
437 	const unsigned end_of_metadata = height - 1;
438 	int eob = 0;
439 	enum alloc_state state;
440 	__be64 *ptr;
441 	__be64 zero_bn = 0;
442 
443 	BUG_ON(sheight < 1);
444 	BUG_ON(dibh == NULL);
445 
446 	gfs2_trans_add_bh(ip->i_gl, dibh, 1);
447 
448 	if (height == sheight) {
449 		struct buffer_head *bh;
450 		/* Bottom indirect block exists, find unalloced extent size */
451 		ptr = metapointer(end_of_metadata, mp);
452 		bh = mp->mp_bh[end_of_metadata];
453 		dblks = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen,
454 					   &eob);
455 		BUG_ON(dblks < 1);
456 		state = ALLOC_DATA;
457 	} else {
458 		/* Need to allocate indirect blocks */
459 		ptrs_per_blk = height > 1 ? sdp->sd_inptrs : sdp->sd_diptrs;
460 		dblks = min(maxlen, ptrs_per_blk - mp->mp_list[end_of_metadata]);
461 		if (height == ip->i_height) {
462 			/* Writing into existing tree, extend tree down */
463 			iblks = height - sheight;
464 			state = ALLOC_GROW_DEPTH;
465 		} else {
466 			/* Building up tree height */
467 			state = ALLOC_GROW_HEIGHT;
468 			iblks = height - ip->i_height;
469 			branch_start = metapath_branch_start(mp);
470 			iblks += (height - branch_start);
471 		}
472 	}
473 
474 	/* start of the second part of the function (state machine) */
475 
476 	blks = dblks + iblks;
477 	i = sheight;
478 	do {
479 		n = blks - alloced;
480 		bn = gfs2_alloc_block(ip, &n);
481 		alloced += n;
482 		if (state != ALLOC_DATA || gfs2_is_jdata(ip))
483 			gfs2_trans_add_unrevoke(sdp, bn, n);
484 		switch (state) {
485 		/* Growing height of tree */
486 		case ALLOC_GROW_HEIGHT:
487 			if (i == 1) {
488 				ptr = (__be64 *)(dibh->b_data +
489 						 sizeof(struct gfs2_dinode));
490 				zero_bn = *ptr;
491 			}
492 			for (; i - 1 < height - ip->i_height && n > 0; i++, n--)
493 				gfs2_indirect_init(mp, ip->i_gl, i, 0, bn++);
494 			if (i - 1 == height - ip->i_height) {
495 				i--;
496 				gfs2_buffer_copy_tail(mp->mp_bh[i],
497 						sizeof(struct gfs2_meta_header),
498 						dibh, sizeof(struct gfs2_dinode));
499 				gfs2_buffer_clear_tail(dibh,
500 						sizeof(struct gfs2_dinode) +
501 						sizeof(__be64));
502 				ptr = (__be64 *)(mp->mp_bh[i]->b_data +
503 					sizeof(struct gfs2_meta_header));
504 				*ptr = zero_bn;
505 				state = ALLOC_GROW_DEPTH;
506 				for(i = branch_start; i < height; i++) {
507 					if (mp->mp_bh[i] == NULL)
508 						break;
509 					brelse(mp->mp_bh[i]);
510 					mp->mp_bh[i] = NULL;
511 				}
512 				i = branch_start;
513 			}
514 			if (n == 0)
515 				break;
516 		/* Branching from existing tree */
517 		case ALLOC_GROW_DEPTH:
518 			if (i > 1 && i < height)
519 				gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[i-1], 1);
520 			for (; i < height && n > 0; i++, n--)
521 				gfs2_indirect_init(mp, ip->i_gl, i,
522 						   mp->mp_list[i-1], bn++);
523 			if (i == height)
524 				state = ALLOC_DATA;
525 			if (n == 0)
526 				break;
527 		/* Tree complete, adding data blocks */
528 		case ALLOC_DATA:
529 			BUG_ON(n > dblks);
530 			BUG_ON(mp->mp_bh[end_of_metadata] == NULL);
531 			gfs2_trans_add_bh(ip->i_gl, mp->mp_bh[end_of_metadata], 1);
532 			dblks = n;
533 			ptr = metapointer(end_of_metadata, mp);
534 			dblock = bn;
535 			while (n-- > 0)
536 				*ptr++ = cpu_to_be64(bn++);
537 			break;
538 		}
539 	} while (state != ALLOC_DATA);
540 
541 	ip->i_height = height;
542 	gfs2_add_inode_blocks(&ip->i_inode, alloced);
543 	gfs2_dinode_out(ip, mp->mp_bh[0]->b_data);
544 	map_bh(bh_map, inode->i_sb, dblock);
545 	bh_map->b_size = dblks << inode->i_blkbits;
546 	set_buffer_new(bh_map);
547 	return 0;
548 }
549 
550 /**
551  * gfs2_block_map - Map a block from an inode to a disk block
552  * @inode: The inode
553  * @lblock: The logical block number
554  * @bh_map: The bh to be mapped
555  * @create: True if its ok to alloc blocks to satify the request
556  *
557  * Sets buffer_mapped() if successful, sets buffer_boundary() if a
558  * read of metadata will be required before the next block can be
559  * mapped. Sets buffer_new() if new blocks were allocated.
560  *
561  * Returns: errno
562  */
563 
564 int gfs2_block_map(struct inode *inode, sector_t lblock,
565 		   struct buffer_head *bh_map, int create)
566 {
567 	struct gfs2_inode *ip = GFS2_I(inode);
568 	struct gfs2_sbd *sdp = GFS2_SB(inode);
569 	unsigned int bsize = sdp->sd_sb.sb_bsize;
570 	const unsigned int maxlen = bh_map->b_size >> inode->i_blkbits;
571 	const u64 *arr = sdp->sd_heightsize;
572 	__be64 *ptr;
573 	u64 size;
574 	struct metapath mp;
575 	int ret;
576 	int eob;
577 	unsigned int len;
578 	struct buffer_head *bh;
579 	u8 height;
580 
581 	BUG_ON(maxlen == 0);
582 
583 	memset(mp.mp_bh, 0, sizeof(mp.mp_bh));
584 	bmap_lock(ip, create);
585 	clear_buffer_mapped(bh_map);
586 	clear_buffer_new(bh_map);
587 	clear_buffer_boundary(bh_map);
588 	if (gfs2_is_dir(ip)) {
589 		bsize = sdp->sd_jbsize;
590 		arr = sdp->sd_jheightsize;
591 	}
592 
593 	ret = gfs2_meta_inode_buffer(ip, &mp.mp_bh[0]);
594 	if (ret)
595 		goto out;
596 
597 	height = ip->i_height;
598 	size = (lblock + 1) * bsize;
599 	while (size > arr[height])
600 		height++;
601 	find_metapath(sdp, lblock, &mp, height);
602 	ret = 1;
603 	if (height > ip->i_height || gfs2_is_stuffed(ip))
604 		goto do_alloc;
605 	ret = lookup_metapath(ip, &mp);
606 	if (ret < 0)
607 		goto out;
608 	if (ret != ip->i_height)
609 		goto do_alloc;
610 	ptr = metapointer(ip->i_height - 1, &mp);
611 	if (*ptr == 0)
612 		goto do_alloc;
613 	map_bh(bh_map, inode->i_sb, be64_to_cpu(*ptr));
614 	bh = mp.mp_bh[ip->i_height - 1];
615 	len = gfs2_extent_length(bh->b_data, bh->b_size, ptr, maxlen, &eob);
616 	bh_map->b_size = (len << inode->i_blkbits);
617 	if (eob)
618 		set_buffer_boundary(bh_map);
619 	ret = 0;
620 out:
621 	release_metapath(&mp);
622 	bmap_unlock(ip, create);
623 	return ret;
624 
625 do_alloc:
626 	/* All allocations are done here, firstly check create flag */
627 	if (!create) {
628 		BUG_ON(gfs2_is_stuffed(ip));
629 		ret = 0;
630 		goto out;
631 	}
632 
633 	/* At this point ret is the tree depth of already allocated blocks */
634 	ret = gfs2_bmap_alloc(inode, lblock, bh_map, &mp, ret, height, maxlen);
635 	goto out;
636 }
637 
638 /*
639  * Deprecated: do not use in new code
640  */
641 int gfs2_extent_map(struct inode *inode, u64 lblock, int *new, u64 *dblock, unsigned *extlen)
642 {
643 	struct buffer_head bh = { .b_state = 0, .b_blocknr = 0 };
644 	int ret;
645 	int create = *new;
646 
647 	BUG_ON(!extlen);
648 	BUG_ON(!dblock);
649 	BUG_ON(!new);
650 
651 	bh.b_size = 1 << (inode->i_blkbits + (create ? 0 : 5));
652 	ret = gfs2_block_map(inode, lblock, &bh, create);
653 	*extlen = bh.b_size >> inode->i_blkbits;
654 	*dblock = bh.b_blocknr;
655 	if (buffer_new(&bh))
656 		*new = 1;
657 	else
658 		*new = 0;
659 	return ret;
660 }
661 
662 /**
663  * recursive_scan - recursively scan through the end of a file
664  * @ip: the inode
665  * @dibh: the dinode buffer
666  * @mp: the path through the metadata to the point to start
667  * @height: the height the recursion is at
668  * @block: the indirect block to look at
669  * @first: 1 if this is the first block
670  * @bc: the call to make for each piece of metadata
671  * @data: data opaque to this function to pass to @bc
672  *
673  * When this is first called @height and @block should be zero and
674  * @first should be 1.
675  *
676  * Returns: errno
677  */
678 
679 static int recursive_scan(struct gfs2_inode *ip, struct buffer_head *dibh,
680 			  struct metapath *mp, unsigned int height,
681 			  u64 block, int first, block_call_t bc,
682 			  void *data)
683 {
684 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
685 	struct buffer_head *bh = NULL;
686 	__be64 *top, *bottom;
687 	u64 bn;
688 	int error;
689 	int mh_size = sizeof(struct gfs2_meta_header);
690 
691 	if (!height) {
692 		error = gfs2_meta_inode_buffer(ip, &bh);
693 		if (error)
694 			return error;
695 		dibh = bh;
696 
697 		top = (__be64 *)(bh->b_data + sizeof(struct gfs2_dinode)) + mp->mp_list[0];
698 		bottom = (__be64 *)(bh->b_data + sizeof(struct gfs2_dinode)) + sdp->sd_diptrs;
699 	} else {
700 		error = gfs2_meta_indirect_buffer(ip, height, block, 0, &bh);
701 		if (error)
702 			return error;
703 
704 		top = (__be64 *)(bh->b_data + mh_size) +
705 				  (first ? mp->mp_list[height] : 0);
706 
707 		bottom = (__be64 *)(bh->b_data + mh_size) + sdp->sd_inptrs;
708 	}
709 
710 	error = bc(ip, dibh, bh, top, bottom, height, data);
711 	if (error)
712 		goto out;
713 
714 	if (height < ip->i_height - 1)
715 		for (; top < bottom; top++, first = 0) {
716 			if (!*top)
717 				continue;
718 
719 			bn = be64_to_cpu(*top);
720 
721 			error = recursive_scan(ip, dibh, mp, height + 1, bn,
722 					       first, bc, data);
723 			if (error)
724 				break;
725 		}
726 
727 out:
728 	brelse(bh);
729 	return error;
730 }
731 
732 /**
733  * do_strip - Look for a layer a particular layer of the file and strip it off
734  * @ip: the inode
735  * @dibh: the dinode buffer
736  * @bh: A buffer of pointers
737  * @top: The first pointer in the buffer
738  * @bottom: One more than the last pointer
739  * @height: the height this buffer is at
740  * @data: a pointer to a struct strip_mine
741  *
742  * Returns: errno
743  */
744 
745 static int do_strip(struct gfs2_inode *ip, struct buffer_head *dibh,
746 		    struct buffer_head *bh, __be64 *top, __be64 *bottom,
747 		    unsigned int height, void *data)
748 {
749 	struct strip_mine *sm = data;
750 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
751 	struct gfs2_rgrp_list rlist;
752 	u64 bn, bstart;
753 	u32 blen;
754 	__be64 *p;
755 	unsigned int rg_blocks = 0;
756 	int metadata;
757 	unsigned int revokes = 0;
758 	int x;
759 	int error;
760 
761 	if (!*top)
762 		sm->sm_first = 0;
763 
764 	if (height != sm->sm_height)
765 		return 0;
766 
767 	if (sm->sm_first) {
768 		top++;
769 		sm->sm_first = 0;
770 	}
771 
772 	metadata = (height != ip->i_height - 1);
773 	if (metadata)
774 		revokes = (height) ? sdp->sd_inptrs : sdp->sd_diptrs;
775 
776 	error = gfs2_rindex_hold(sdp, &ip->i_alloc->al_ri_gh);
777 	if (error)
778 		return error;
779 
780 	memset(&rlist, 0, sizeof(struct gfs2_rgrp_list));
781 	bstart = 0;
782 	blen = 0;
783 
784 	for (p = top; p < bottom; p++) {
785 		if (!*p)
786 			continue;
787 
788 		bn = be64_to_cpu(*p);
789 
790 		if (bstart + blen == bn)
791 			blen++;
792 		else {
793 			if (bstart)
794 				gfs2_rlist_add(sdp, &rlist, bstart);
795 
796 			bstart = bn;
797 			blen = 1;
798 		}
799 	}
800 
801 	if (bstart)
802 		gfs2_rlist_add(sdp, &rlist, bstart);
803 	else
804 		goto out; /* Nothing to do */
805 
806 	gfs2_rlist_alloc(&rlist, LM_ST_EXCLUSIVE);
807 
808 	for (x = 0; x < rlist.rl_rgrps; x++) {
809 		struct gfs2_rgrpd *rgd;
810 		rgd = rlist.rl_ghs[x].gh_gl->gl_object;
811 		rg_blocks += rgd->rd_length;
812 	}
813 
814 	error = gfs2_glock_nq_m(rlist.rl_rgrps, rlist.rl_ghs);
815 	if (error)
816 		goto out_rlist;
817 
818 	error = gfs2_trans_begin(sdp, rg_blocks + RES_DINODE +
819 				 RES_INDIRECT + RES_STATFS + RES_QUOTA,
820 				 revokes);
821 	if (error)
822 		goto out_rg_gunlock;
823 
824 	down_write(&ip->i_rw_mutex);
825 
826 	gfs2_trans_add_bh(ip->i_gl, dibh, 1);
827 	gfs2_trans_add_bh(ip->i_gl, bh, 1);
828 
829 	bstart = 0;
830 	blen = 0;
831 
832 	for (p = top; p < bottom; p++) {
833 		if (!*p)
834 			continue;
835 
836 		bn = be64_to_cpu(*p);
837 
838 		if (bstart + blen == bn)
839 			blen++;
840 		else {
841 			if (bstart) {
842 				if (metadata)
843 					gfs2_free_meta(ip, bstart, blen);
844 				else
845 					gfs2_free_data(ip, bstart, blen);
846 			}
847 
848 			bstart = bn;
849 			blen = 1;
850 		}
851 
852 		*p = 0;
853 		gfs2_add_inode_blocks(&ip->i_inode, -1);
854 	}
855 	if (bstart) {
856 		if (metadata)
857 			gfs2_free_meta(ip, bstart, blen);
858 		else
859 			gfs2_free_data(ip, bstart, blen);
860 	}
861 
862 	ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
863 
864 	gfs2_dinode_out(ip, dibh->b_data);
865 
866 	up_write(&ip->i_rw_mutex);
867 
868 	gfs2_trans_end(sdp);
869 
870 out_rg_gunlock:
871 	gfs2_glock_dq_m(rlist.rl_rgrps, rlist.rl_ghs);
872 out_rlist:
873 	gfs2_rlist_free(&rlist);
874 out:
875 	gfs2_glock_dq_uninit(&ip->i_alloc->al_ri_gh);
876 	return error;
877 }
878 
879 /**
880  * do_grow - Make a file look bigger than it is
881  * @ip: the inode
882  * @size: the size to set the file to
883  *
884  * Called with an exclusive lock on @ip.
885  *
886  * Returns: errno
887  */
888 
889 static int do_grow(struct gfs2_inode *ip, u64 size)
890 {
891 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
892 	struct gfs2_alloc *al;
893 	struct buffer_head *dibh;
894 	int error;
895 
896 	al = gfs2_alloc_get(ip);
897 	if (!al)
898 		return -ENOMEM;
899 
900 	error = gfs2_quota_lock_check(ip);
901 	if (error)
902 		goto out;
903 
904 	al->al_requested = sdp->sd_max_height + RES_DATA;
905 
906 	error = gfs2_inplace_reserve(ip);
907 	if (error)
908 		goto out_gunlock_q;
909 
910 	error = gfs2_trans_begin(sdp,
911 			sdp->sd_max_height + al->al_rgd->rd_length +
912 			RES_JDATA + RES_DINODE + RES_STATFS + RES_QUOTA, 0);
913 	if (error)
914 		goto out_ipres;
915 
916 	error = gfs2_meta_inode_buffer(ip, &dibh);
917 	if (error)
918 		goto out_end_trans;
919 
920 	if (size > sdp->sd_sb.sb_bsize - sizeof(struct gfs2_dinode)) {
921 		if (gfs2_is_stuffed(ip)) {
922 			error = gfs2_unstuff_dinode(ip, NULL);
923 			if (error)
924 				goto out_brelse;
925 		}
926 	}
927 
928 	ip->i_disksize = size;
929 	ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
930 	gfs2_trans_add_bh(ip->i_gl, dibh, 1);
931 	gfs2_dinode_out(ip, dibh->b_data);
932 
933 out_brelse:
934 	brelse(dibh);
935 out_end_trans:
936 	gfs2_trans_end(sdp);
937 out_ipres:
938 	gfs2_inplace_release(ip);
939 out_gunlock_q:
940 	gfs2_quota_unlock(ip);
941 out:
942 	gfs2_alloc_put(ip);
943 	return error;
944 }
945 
946 
947 /**
948  * gfs2_block_truncate_page - Deal with zeroing out data for truncate
949  *
950  * This is partly borrowed from ext3.
951  */
952 static int gfs2_block_truncate_page(struct address_space *mapping)
953 {
954 	struct inode *inode = mapping->host;
955 	struct gfs2_inode *ip = GFS2_I(inode);
956 	loff_t from = inode->i_size;
957 	unsigned long index = from >> PAGE_CACHE_SHIFT;
958 	unsigned offset = from & (PAGE_CACHE_SIZE-1);
959 	unsigned blocksize, iblock, length, pos;
960 	struct buffer_head *bh;
961 	struct page *page;
962 	int err;
963 
964 	page = grab_cache_page(mapping, index);
965 	if (!page)
966 		return 0;
967 
968 	blocksize = inode->i_sb->s_blocksize;
969 	length = blocksize - (offset & (blocksize - 1));
970 	iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
971 
972 	if (!page_has_buffers(page))
973 		create_empty_buffers(page, blocksize, 0);
974 
975 	/* Find the buffer that contains "offset" */
976 	bh = page_buffers(page);
977 	pos = blocksize;
978 	while (offset >= pos) {
979 		bh = bh->b_this_page;
980 		iblock++;
981 		pos += blocksize;
982 	}
983 
984 	err = 0;
985 
986 	if (!buffer_mapped(bh)) {
987 		gfs2_block_map(inode, iblock, bh, 0);
988 		/* unmapped? It's a hole - nothing to do */
989 		if (!buffer_mapped(bh))
990 			goto unlock;
991 	}
992 
993 	/* Ok, it's mapped. Make sure it's up-to-date */
994 	if (PageUptodate(page))
995 		set_buffer_uptodate(bh);
996 
997 	if (!buffer_uptodate(bh)) {
998 		err = -EIO;
999 		ll_rw_block(READ, 1, &bh);
1000 		wait_on_buffer(bh);
1001 		/* Uhhuh. Read error. Complain and punt. */
1002 		if (!buffer_uptodate(bh))
1003 			goto unlock;
1004 		err = 0;
1005 	}
1006 
1007 	if (!gfs2_is_writeback(ip))
1008 		gfs2_trans_add_bh(ip->i_gl, bh, 0);
1009 
1010 	zero_user(page, offset, length);
1011 
1012 unlock:
1013 	unlock_page(page);
1014 	page_cache_release(page);
1015 	return err;
1016 }
1017 
1018 static int trunc_start(struct gfs2_inode *ip, u64 size)
1019 {
1020 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
1021 	struct buffer_head *dibh;
1022 	int journaled = gfs2_is_jdata(ip);
1023 	int error;
1024 
1025 	error = gfs2_trans_begin(sdp,
1026 				 RES_DINODE + (journaled ? RES_JDATA : 0), 0);
1027 	if (error)
1028 		return error;
1029 
1030 	error = gfs2_meta_inode_buffer(ip, &dibh);
1031 	if (error)
1032 		goto out;
1033 
1034 	if (gfs2_is_stuffed(ip)) {
1035 		ip->i_disksize = size;
1036 		ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
1037 		gfs2_trans_add_bh(ip->i_gl, dibh, 1);
1038 		gfs2_dinode_out(ip, dibh->b_data);
1039 		gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode) + size);
1040 		error = 1;
1041 
1042 	} else {
1043 		if (size & (u64)(sdp->sd_sb.sb_bsize - 1))
1044 			error = gfs2_block_truncate_page(ip->i_inode.i_mapping);
1045 
1046 		if (!error) {
1047 			ip->i_disksize = size;
1048 			ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
1049 			ip->i_diskflags |= GFS2_DIF_TRUNC_IN_PROG;
1050 			gfs2_trans_add_bh(ip->i_gl, dibh, 1);
1051 			gfs2_dinode_out(ip, dibh->b_data);
1052 		}
1053 	}
1054 
1055 	brelse(dibh);
1056 
1057 out:
1058 	gfs2_trans_end(sdp);
1059 	return error;
1060 }
1061 
1062 static int trunc_dealloc(struct gfs2_inode *ip, u64 size)
1063 {
1064 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
1065 	unsigned int height = ip->i_height;
1066 	u64 lblock;
1067 	struct metapath mp;
1068 	int error;
1069 
1070 	if (!size)
1071 		lblock = 0;
1072 	else
1073 		lblock = (size - 1) >> sdp->sd_sb.sb_bsize_shift;
1074 
1075 	find_metapath(sdp, lblock, &mp, ip->i_height);
1076 	if (!gfs2_alloc_get(ip))
1077 		return -ENOMEM;
1078 
1079 	error = gfs2_quota_hold(ip, NO_QUOTA_CHANGE, NO_QUOTA_CHANGE);
1080 	if (error)
1081 		goto out;
1082 
1083 	while (height--) {
1084 		struct strip_mine sm;
1085 		sm.sm_first = !!size;
1086 		sm.sm_height = height;
1087 
1088 		error = recursive_scan(ip, NULL, &mp, 0, 0, 1, do_strip, &sm);
1089 		if (error)
1090 			break;
1091 	}
1092 
1093 	gfs2_quota_unhold(ip);
1094 
1095 out:
1096 	gfs2_alloc_put(ip);
1097 	return error;
1098 }
1099 
1100 static int trunc_end(struct gfs2_inode *ip)
1101 {
1102 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
1103 	struct buffer_head *dibh;
1104 	int error;
1105 
1106 	error = gfs2_trans_begin(sdp, RES_DINODE, 0);
1107 	if (error)
1108 		return error;
1109 
1110 	down_write(&ip->i_rw_mutex);
1111 
1112 	error = gfs2_meta_inode_buffer(ip, &dibh);
1113 	if (error)
1114 		goto out;
1115 
1116 	if (!ip->i_disksize) {
1117 		ip->i_height = 0;
1118 		ip->i_goal = ip->i_no_addr;
1119 		gfs2_buffer_clear_tail(dibh, sizeof(struct gfs2_dinode));
1120 	}
1121 	ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
1122 	ip->i_diskflags &= ~GFS2_DIF_TRUNC_IN_PROG;
1123 
1124 	gfs2_trans_add_bh(ip->i_gl, dibh, 1);
1125 	gfs2_dinode_out(ip, dibh->b_data);
1126 	brelse(dibh);
1127 
1128 out:
1129 	up_write(&ip->i_rw_mutex);
1130 	gfs2_trans_end(sdp);
1131 	return error;
1132 }
1133 
1134 /**
1135  * do_shrink - make a file smaller
1136  * @ip: the inode
1137  * @size: the size to make the file
1138  * @truncator: function to truncate the last partial block
1139  *
1140  * Called with an exclusive lock on @ip.
1141  *
1142  * Returns: errno
1143  */
1144 
1145 static int do_shrink(struct gfs2_inode *ip, u64 size)
1146 {
1147 	int error;
1148 
1149 	error = trunc_start(ip, size);
1150 	if (error < 0)
1151 		return error;
1152 	if (error > 0)
1153 		return 0;
1154 
1155 	error = trunc_dealloc(ip, size);
1156 	if (!error)
1157 		error = trunc_end(ip);
1158 
1159 	return error;
1160 }
1161 
1162 static int do_touch(struct gfs2_inode *ip, u64 size)
1163 {
1164 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
1165 	struct buffer_head *dibh;
1166 	int error;
1167 
1168 	error = gfs2_trans_begin(sdp, RES_DINODE, 0);
1169 	if (error)
1170 		return error;
1171 
1172 	down_write(&ip->i_rw_mutex);
1173 
1174 	error = gfs2_meta_inode_buffer(ip, &dibh);
1175 	if (error)
1176 		goto do_touch_out;
1177 
1178 	ip->i_inode.i_mtime = ip->i_inode.i_ctime = CURRENT_TIME;
1179 	gfs2_trans_add_bh(ip->i_gl, dibh, 1);
1180 	gfs2_dinode_out(ip, dibh->b_data);
1181 	brelse(dibh);
1182 
1183 do_touch_out:
1184 	up_write(&ip->i_rw_mutex);
1185 	gfs2_trans_end(sdp);
1186 	return error;
1187 }
1188 
1189 /**
1190  * gfs2_truncatei - make a file a given size
1191  * @ip: the inode
1192  * @size: the size to make the file
1193  * @truncator: function to truncate the last partial block
1194  *
1195  * The file size can grow, shrink, or stay the same size.
1196  *
1197  * Returns: errno
1198  */
1199 
1200 int gfs2_truncatei(struct gfs2_inode *ip, u64 size)
1201 {
1202 	int error;
1203 
1204 	if (gfs2_assert_warn(GFS2_SB(&ip->i_inode), S_ISREG(ip->i_inode.i_mode)))
1205 		return -EINVAL;
1206 
1207 	if (size > ip->i_disksize)
1208 		error = do_grow(ip, size);
1209 	else if (size < ip->i_disksize)
1210 		error = do_shrink(ip, size);
1211 	else
1212 		/* update time stamps */
1213 		error = do_touch(ip, size);
1214 
1215 	return error;
1216 }
1217 
1218 int gfs2_truncatei_resume(struct gfs2_inode *ip)
1219 {
1220 	int error;
1221 	error = trunc_dealloc(ip, ip->i_disksize);
1222 	if (!error)
1223 		error = trunc_end(ip);
1224 	return error;
1225 }
1226 
1227 int gfs2_file_dealloc(struct gfs2_inode *ip)
1228 {
1229 	return trunc_dealloc(ip, 0);
1230 }
1231 
1232 /**
1233  * gfs2_write_alloc_required - figure out if a write will require an allocation
1234  * @ip: the file being written to
1235  * @offset: the offset to write to
1236  * @len: the number of bytes being written
1237  * @alloc_required: set to 1 if an alloc is required, 0 otherwise
1238  *
1239  * Returns: errno
1240  */
1241 
1242 int gfs2_write_alloc_required(struct gfs2_inode *ip, u64 offset,
1243 			      unsigned int len, int *alloc_required)
1244 {
1245 	struct gfs2_sbd *sdp = GFS2_SB(&ip->i_inode);
1246 	struct buffer_head bh;
1247 	unsigned int shift;
1248 	u64 lblock, lblock_stop, size;
1249 	u64 end_of_file;
1250 
1251 	*alloc_required = 0;
1252 
1253 	if (!len)
1254 		return 0;
1255 
1256 	if (gfs2_is_stuffed(ip)) {
1257 		if (offset + len >
1258 		    sdp->sd_sb.sb_bsize - sizeof(struct gfs2_dinode))
1259 			*alloc_required = 1;
1260 		return 0;
1261 	}
1262 
1263 	*alloc_required = 1;
1264 	shift = sdp->sd_sb.sb_bsize_shift;
1265 	BUG_ON(gfs2_is_dir(ip));
1266 	end_of_file = (ip->i_disksize + sdp->sd_sb.sb_bsize - 1) >> shift;
1267 	lblock = offset >> shift;
1268 	lblock_stop = (offset + len + sdp->sd_sb.sb_bsize - 1) >> shift;
1269 	if (lblock_stop > end_of_file)
1270 		return 0;
1271 
1272 	size = (lblock_stop - lblock) << shift;
1273 	do {
1274 		bh.b_state = 0;
1275 		bh.b_size = size;
1276 		gfs2_block_map(&ip->i_inode, lblock, &bh, 0);
1277 		if (!buffer_mapped(&bh))
1278 			return 0;
1279 		size -= bh.b_size;
1280 		lblock += (bh.b_size >> ip->i_inode.i_blkbits);
1281 	} while(size > 0);
1282 
1283 	*alloc_required = 0;
1284 	return 0;
1285 }
1286 
1287