• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *   Copyright (C) International Business Machines Corp., 2000-2004
4  *   Portions Copyright (C) Tino Reichardt, 2012
5  */
6 
7 #include <linux/fs.h>
8 #include <linux/slab.h>
9 #include "jfs_incore.h"
10 #include "jfs_superblock.h"
11 #include "jfs_dmap.h"
12 #include "jfs_imap.h"
13 #include "jfs_lock.h"
14 #include "jfs_metapage.h"
15 #include "jfs_debug.h"
16 #include "jfs_discard.h"
17 
18 /*
19  *	SERIALIZATION of the Block Allocation Map.
20  *
21  *	the working state of the block allocation map is accessed in
22  *	two directions:
23  *
24  *	1) allocation and free requests that start at the dmap
25  *	   level and move up through the dmap control pages (i.e.
26  *	   the vast majority of requests).
27  *
28  *	2) allocation requests that start at dmap control page
29  *	   level and work down towards the dmaps.
30  *
31  *	the serialization scheme used here is as follows.
32  *
33  *	requests which start at the bottom are serialized against each
34  *	other through buffers and each requests holds onto its buffers
35  *	as it works it way up from a single dmap to the required level
36  *	of dmap control page.
37  *	requests that start at the top are serialized against each other
38  *	and request that start from the bottom by the multiple read/single
39  *	write inode lock of the bmap inode. requests starting at the top
40  *	take this lock in write mode while request starting at the bottom
41  *	take the lock in read mode.  a single top-down request may proceed
42  *	exclusively while multiple bottoms-up requests may proceed
43  *	simultaneously (under the protection of busy buffers).
44  *
45  *	in addition to information found in dmaps and dmap control pages,
46  *	the working state of the block allocation map also includes read/
47  *	write information maintained in the bmap descriptor (i.e. total
48  *	free block count, allocation group level free block counts).
49  *	a single exclusive lock (BMAP_LOCK) is used to guard this information
50  *	in the face of multiple-bottoms up requests.
51  *	(lock ordering: IREAD_LOCK, BMAP_LOCK);
52  *
53  *	accesses to the persistent state of the block allocation map (limited
54  *	to the persistent bitmaps in dmaps) is guarded by (busy) buffers.
55  */
56 
57 #define BMAP_LOCK_INIT(bmp)	mutex_init(&bmp->db_bmaplock)
58 #define BMAP_LOCK(bmp)		mutex_lock(&bmp->db_bmaplock)
59 #define BMAP_UNLOCK(bmp)	mutex_unlock(&bmp->db_bmaplock)
60 
61 /*
62  * forward references
63  */
64 static void dbAllocBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
65 			int nblocks);
66 static void dbSplit(dmtree_t * tp, int leafno, int splitsz, int newval);
67 static int dbBackSplit(dmtree_t * tp, int leafno);
68 static int dbJoin(dmtree_t * tp, int leafno, int newval);
69 static void dbAdjTree(dmtree_t * tp, int leafno, int newval);
70 static int dbAdjCtl(struct bmap * bmp, s64 blkno, int newval, int alloc,
71 		    int level);
72 static int dbAllocAny(struct bmap * bmp, s64 nblocks, int l2nb, s64 * results);
73 static int dbAllocNext(struct bmap * bmp, struct dmap * dp, s64 blkno,
74 		       int nblocks);
75 static int dbAllocNear(struct bmap * bmp, struct dmap * dp, s64 blkno,
76 		       int nblocks,
77 		       int l2nb, s64 * results);
78 static int dbAllocDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
79 		       int nblocks);
80 static int dbAllocDmapLev(struct bmap * bmp, struct dmap * dp, int nblocks,
81 			  int l2nb,
82 			  s64 * results);
83 static int dbAllocAG(struct bmap * bmp, int agno, s64 nblocks, int l2nb,
84 		     s64 * results);
85 static int dbAllocCtl(struct bmap * bmp, s64 nblocks, int l2nb, s64 blkno,
86 		      s64 * results);
87 static int dbExtend(struct inode *ip, s64 blkno, s64 nblocks, s64 addnblocks);
88 static int dbFindBits(u32 word, int l2nb);
89 static int dbFindCtl(struct bmap * bmp, int l2nb, int level, s64 * blkno);
90 static int dbFindLeaf(dmtree_t * tp, int l2nb, int *leafidx);
91 static int dbFreeBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
92 		      int nblocks);
93 static int dbFreeDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
94 		      int nblocks);
95 static int dbMaxBud(u8 * cp);
96 static int blkstol2(s64 nb);
97 
98 static int cntlz(u32 value);
99 static int cnttz(u32 word);
100 
101 static int dbAllocDmapBU(struct bmap * bmp, struct dmap * dp, s64 blkno,
102 			 int nblocks);
103 static int dbInitDmap(struct dmap * dp, s64 blkno, int nblocks);
104 static int dbInitDmapTree(struct dmap * dp);
105 static int dbInitTree(struct dmaptree * dtp);
106 static int dbInitDmapCtl(struct dmapctl * dcp, int level, int i);
107 static int dbGetL2AGSize(s64 nblocks);
108 
109 /*
110  *	buddy table
111  *
112  * table used for determining buddy sizes within characters of
113  * dmap bitmap words.  the characters themselves serve as indexes
114  * into the table, with the table elements yielding the maximum
115  * binary buddy of free bits within the character.
116  */
117 static const s8 budtab[256] = {
118 	3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
119 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
120 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
121 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
122 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
123 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
124 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
125 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
126 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
127 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
128 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
129 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
130 	2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
131 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
132 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
133 	2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -1
134 };
135 
136 /*
137  * NAME:	dbMount()
138  *
139  * FUNCTION:	initializate the block allocation map.
140  *
141  *		memory is allocated for the in-core bmap descriptor and
142  *		the in-core descriptor is initialized from disk.
143  *
144  * PARAMETERS:
145  *	ipbmap	- pointer to in-core inode for the block map.
146  *
147  * RETURN VALUES:
148  *	0	- success
149  *	-ENOMEM	- insufficient memory
150  *	-EIO	- i/o error
151  *	-EINVAL - wrong bmap data
152  */
dbMount(struct inode * ipbmap)153 int dbMount(struct inode *ipbmap)
154 {
155 	struct bmap *bmp;
156 	struct dbmap_disk *dbmp_le;
157 	struct metapage *mp;
158 	int i, err;
159 
160 	/*
161 	 * allocate/initialize the in-memory bmap descriptor
162 	 */
163 	/* allocate memory for the in-memory bmap descriptor */
164 	bmp = kmalloc(sizeof(struct bmap), GFP_KERNEL);
165 	if (bmp == NULL)
166 		return -ENOMEM;
167 
168 	/* read the on-disk bmap descriptor. */
169 	mp = read_metapage(ipbmap,
170 			   BMAPBLKNO << JFS_SBI(ipbmap->i_sb)->l2nbperpage,
171 			   PSIZE, 0);
172 	if (mp == NULL) {
173 		err = -EIO;
174 		goto err_kfree_bmp;
175 	}
176 
177 	/* copy the on-disk bmap descriptor to its in-memory version. */
178 	dbmp_le = (struct dbmap_disk *) mp->data;
179 	bmp->db_mapsize = le64_to_cpu(dbmp_le->dn_mapsize);
180 	bmp->db_nfree = le64_to_cpu(dbmp_le->dn_nfree);
181 	bmp->db_l2nbperpage = le32_to_cpu(dbmp_le->dn_l2nbperpage);
182 	bmp->db_numag = le32_to_cpu(dbmp_le->dn_numag);
183 	if (!bmp->db_numag) {
184 		err = -EINVAL;
185 		goto err_release_metapage;
186 	}
187 
188 	bmp->db_maxlevel = le32_to_cpu(dbmp_le->dn_maxlevel);
189 	bmp->db_maxag = le32_to_cpu(dbmp_le->dn_maxag);
190 	bmp->db_agpref = le32_to_cpu(dbmp_le->dn_agpref);
191 	bmp->db_aglevel = le32_to_cpu(dbmp_le->dn_aglevel);
192 	bmp->db_agheight = le32_to_cpu(dbmp_le->dn_agheight);
193 	bmp->db_agwidth = le32_to_cpu(dbmp_le->dn_agwidth);
194 	bmp->db_agstart = le32_to_cpu(dbmp_le->dn_agstart);
195 	bmp->db_agl2size = le32_to_cpu(dbmp_le->dn_agl2size);
196 	if (bmp->db_agl2size > L2MAXL2SIZE - L2MAXAG ||
197 	    bmp->db_agl2size < 0) {
198 		err = -EINVAL;
199 		goto err_release_metapage;
200 	}
201 
202 	if (((bmp->db_mapsize - 1) >> bmp->db_agl2size) > MAXAG) {
203 		err = -EINVAL;
204 		goto err_release_metapage;
205 	}
206 
207 	for (i = 0; i < MAXAG; i++)
208 		bmp->db_agfree[i] = le64_to_cpu(dbmp_le->dn_agfree[i]);
209 	bmp->db_agsize = le64_to_cpu(dbmp_le->dn_agsize);
210 	bmp->db_maxfreebud = dbmp_le->dn_maxfreebud;
211 
212 	/* release the buffer. */
213 	release_metapage(mp);
214 
215 	/* bind the bmap inode and the bmap descriptor to each other. */
216 	bmp->db_ipbmap = ipbmap;
217 	JFS_SBI(ipbmap->i_sb)->bmap = bmp;
218 
219 	memset(bmp->db_active, 0, sizeof(bmp->db_active));
220 
221 	/*
222 	 * allocate/initialize the bmap lock
223 	 */
224 	BMAP_LOCK_INIT(bmp);
225 
226 	return (0);
227 
228 err_release_metapage:
229 	release_metapage(mp);
230 err_kfree_bmp:
231 	kfree(bmp);
232 	return err;
233 }
234 
235 
236 /*
237  * NAME:	dbUnmount()
238  *
239  * FUNCTION:	terminate the block allocation map in preparation for
240  *		file system unmount.
241  *
242  *		the in-core bmap descriptor is written to disk and
243  *		the memory for this descriptor is freed.
244  *
245  * PARAMETERS:
246  *	ipbmap	- pointer to in-core inode for the block map.
247  *
248  * RETURN VALUES:
249  *	0	- success
250  *	-EIO	- i/o error
251  */
dbUnmount(struct inode * ipbmap,int mounterror)252 int dbUnmount(struct inode *ipbmap, int mounterror)
253 {
254 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
255 
256 	if (!(mounterror || isReadOnly(ipbmap)))
257 		dbSync(ipbmap);
258 
259 	/*
260 	 * Invalidate the page cache buffers
261 	 */
262 	truncate_inode_pages(ipbmap->i_mapping, 0);
263 
264 	/* free the memory for the in-memory bmap. */
265 	kfree(bmp);
266 
267 	return (0);
268 }
269 
270 /*
271  *	dbSync()
272  */
dbSync(struct inode * ipbmap)273 int dbSync(struct inode *ipbmap)
274 {
275 	struct dbmap_disk *dbmp_le;
276 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
277 	struct metapage *mp;
278 	int i;
279 
280 	/*
281 	 * write bmap global control page
282 	 */
283 	/* get the buffer for the on-disk bmap descriptor. */
284 	mp = read_metapage(ipbmap,
285 			   BMAPBLKNO << JFS_SBI(ipbmap->i_sb)->l2nbperpage,
286 			   PSIZE, 0);
287 	if (mp == NULL) {
288 		jfs_err("dbSync: read_metapage failed!");
289 		return -EIO;
290 	}
291 	/* copy the in-memory version of the bmap to the on-disk version */
292 	dbmp_le = (struct dbmap_disk *) mp->data;
293 	dbmp_le->dn_mapsize = cpu_to_le64(bmp->db_mapsize);
294 	dbmp_le->dn_nfree = cpu_to_le64(bmp->db_nfree);
295 	dbmp_le->dn_l2nbperpage = cpu_to_le32(bmp->db_l2nbperpage);
296 	dbmp_le->dn_numag = cpu_to_le32(bmp->db_numag);
297 	dbmp_le->dn_maxlevel = cpu_to_le32(bmp->db_maxlevel);
298 	dbmp_le->dn_maxag = cpu_to_le32(bmp->db_maxag);
299 	dbmp_le->dn_agpref = cpu_to_le32(bmp->db_agpref);
300 	dbmp_le->dn_aglevel = cpu_to_le32(bmp->db_aglevel);
301 	dbmp_le->dn_agheight = cpu_to_le32(bmp->db_agheight);
302 	dbmp_le->dn_agwidth = cpu_to_le32(bmp->db_agwidth);
303 	dbmp_le->dn_agstart = cpu_to_le32(bmp->db_agstart);
304 	dbmp_le->dn_agl2size = cpu_to_le32(bmp->db_agl2size);
305 	for (i = 0; i < MAXAG; i++)
306 		dbmp_le->dn_agfree[i] = cpu_to_le64(bmp->db_agfree[i]);
307 	dbmp_le->dn_agsize = cpu_to_le64(bmp->db_agsize);
308 	dbmp_le->dn_maxfreebud = bmp->db_maxfreebud;
309 
310 	/* write the buffer */
311 	write_metapage(mp);
312 
313 	/*
314 	 * write out dirty pages of bmap
315 	 */
316 	filemap_write_and_wait(ipbmap->i_mapping);
317 
318 	diWriteSpecial(ipbmap, 0);
319 
320 	return (0);
321 }
322 
323 /*
324  * NAME:	dbFree()
325  *
326  * FUNCTION:	free the specified block range from the working block
327  *		allocation map.
328  *
329  *		the blocks will be free from the working map one dmap
330  *		at a time.
331  *
332  * PARAMETERS:
333  *	ip	- pointer to in-core inode;
334  *	blkno	- starting block number to be freed.
335  *	nblocks	- number of blocks to be freed.
336  *
337  * RETURN VALUES:
338  *	0	- success
339  *	-EIO	- i/o error
340  */
dbFree(struct inode * ip,s64 blkno,s64 nblocks)341 int dbFree(struct inode *ip, s64 blkno, s64 nblocks)
342 {
343 	struct metapage *mp;
344 	struct dmap *dp;
345 	int nb, rc;
346 	s64 lblkno, rem;
347 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
348 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
349 	struct super_block *sb = ipbmap->i_sb;
350 
351 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
352 
353 	/* block to be freed better be within the mapsize. */
354 	if (unlikely((blkno == 0) || (blkno + nblocks > bmp->db_mapsize))) {
355 		IREAD_UNLOCK(ipbmap);
356 		printk(KERN_ERR "blkno = %Lx, nblocks = %Lx\n",
357 		       (unsigned long long) blkno,
358 		       (unsigned long long) nblocks);
359 		jfs_error(ip->i_sb, "block to be freed is outside the map\n");
360 		return -EIO;
361 	}
362 
363 	/**
364 	 * TRIM the blocks, when mounted with discard option
365 	 */
366 	if (JFS_SBI(sb)->flag & JFS_DISCARD)
367 		if (JFS_SBI(sb)->minblks_trim <= nblocks)
368 			jfs_issue_discard(ipbmap, blkno, nblocks);
369 
370 	/*
371 	 * free the blocks a dmap at a time.
372 	 */
373 	mp = NULL;
374 	for (rem = nblocks; rem > 0; rem -= nb, blkno += nb) {
375 		/* release previous dmap if any */
376 		if (mp) {
377 			write_metapage(mp);
378 		}
379 
380 		/* get the buffer for the current dmap. */
381 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
382 		mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
383 		if (mp == NULL) {
384 			IREAD_UNLOCK(ipbmap);
385 			return -EIO;
386 		}
387 		dp = (struct dmap *) mp->data;
388 
389 		/* determine the number of blocks to be freed from
390 		 * this dmap.
391 		 */
392 		nb = min(rem, BPERDMAP - (blkno & (BPERDMAP - 1)));
393 
394 		/* free the blocks. */
395 		if ((rc = dbFreeDmap(bmp, dp, blkno, nb))) {
396 			jfs_error(ip->i_sb, "error in block map\n");
397 			release_metapage(mp);
398 			IREAD_UNLOCK(ipbmap);
399 			return (rc);
400 		}
401 	}
402 
403 	/* write the last buffer. */
404 	if (mp)
405 		write_metapage(mp);
406 
407 	IREAD_UNLOCK(ipbmap);
408 
409 	return (0);
410 }
411 
412 
413 /*
414  * NAME:	dbUpdatePMap()
415  *
416  * FUNCTION:	update the allocation state (free or allocate) of the
417  *		specified block range in the persistent block allocation map.
418  *
419  *		the blocks will be updated in the persistent map one
420  *		dmap at a time.
421  *
422  * PARAMETERS:
423  *	ipbmap	- pointer to in-core inode for the block map.
424  *	free	- 'true' if block range is to be freed from the persistent
425  *		  map; 'false' if it is to be allocated.
426  *	blkno	- starting block number of the range.
427  *	nblocks	- number of contiguous blocks in the range.
428  *	tblk	- transaction block;
429  *
430  * RETURN VALUES:
431  *	0	- success
432  *	-EIO	- i/o error
433  */
434 int
dbUpdatePMap(struct inode * ipbmap,int free,s64 blkno,s64 nblocks,struct tblock * tblk)435 dbUpdatePMap(struct inode *ipbmap,
436 	     int free, s64 blkno, s64 nblocks, struct tblock * tblk)
437 {
438 	int nblks, dbitno, wbitno, rbits;
439 	int word, nbits, nwords;
440 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
441 	s64 lblkno, rem, lastlblkno;
442 	u32 mask;
443 	struct dmap *dp;
444 	struct metapage *mp;
445 	struct jfs_log *log;
446 	int lsn, difft, diffp;
447 	unsigned long flags;
448 
449 	/* the blocks better be within the mapsize. */
450 	if (blkno + nblocks > bmp->db_mapsize) {
451 		printk(KERN_ERR "blkno = %Lx, nblocks = %Lx\n",
452 		       (unsigned long long) blkno,
453 		       (unsigned long long) nblocks);
454 		jfs_error(ipbmap->i_sb, "blocks are outside the map\n");
455 		return -EIO;
456 	}
457 
458 	/* compute delta of transaction lsn from log syncpt */
459 	lsn = tblk->lsn;
460 	log = (struct jfs_log *) JFS_SBI(tblk->sb)->log;
461 	logdiff(difft, lsn, log);
462 
463 	/*
464 	 * update the block state a dmap at a time.
465 	 */
466 	mp = NULL;
467 	lastlblkno = 0;
468 	for (rem = nblocks; rem > 0; rem -= nblks, blkno += nblks) {
469 		/* get the buffer for the current dmap. */
470 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
471 		if (lblkno != lastlblkno) {
472 			if (mp) {
473 				write_metapage(mp);
474 			}
475 
476 			mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE,
477 					   0);
478 			if (mp == NULL)
479 				return -EIO;
480 			metapage_wait_for_io(mp);
481 		}
482 		dp = (struct dmap *) mp->data;
483 
484 		/* determine the bit number and word within the dmap of
485 		 * the starting block.  also determine how many blocks
486 		 * are to be updated within this dmap.
487 		 */
488 		dbitno = blkno & (BPERDMAP - 1);
489 		word = dbitno >> L2DBWORD;
490 		nblks = min(rem, (s64)BPERDMAP - dbitno);
491 
492 		/* update the bits of the dmap words. the first and last
493 		 * words may only have a subset of their bits updated. if
494 		 * this is the case, we'll work against that word (i.e.
495 		 * partial first and/or last) only in a single pass.  a
496 		 * single pass will also be used to update all words that
497 		 * are to have all their bits updated.
498 		 */
499 		for (rbits = nblks; rbits > 0;
500 		     rbits -= nbits, dbitno += nbits) {
501 			/* determine the bit number within the word and
502 			 * the number of bits within the word.
503 			 */
504 			wbitno = dbitno & (DBWORD - 1);
505 			nbits = min(rbits, DBWORD - wbitno);
506 
507 			/* check if only part of the word is to be updated. */
508 			if (nbits < DBWORD) {
509 				/* update (free or allocate) the bits
510 				 * in this word.
511 				 */
512 				mask =
513 				    (ONES << (DBWORD - nbits) >> wbitno);
514 				if (free)
515 					dp->pmap[word] &=
516 					    cpu_to_le32(~mask);
517 				else
518 					dp->pmap[word] |=
519 					    cpu_to_le32(mask);
520 
521 				word += 1;
522 			} else {
523 				/* one or more words are to have all
524 				 * their bits updated.  determine how
525 				 * many words and how many bits.
526 				 */
527 				nwords = rbits >> L2DBWORD;
528 				nbits = nwords << L2DBWORD;
529 
530 				/* update (free or allocate) the bits
531 				 * in these words.
532 				 */
533 				if (free)
534 					memset(&dp->pmap[word], 0,
535 					       nwords * 4);
536 				else
537 					memset(&dp->pmap[word], (int) ONES,
538 					       nwords * 4);
539 
540 				word += nwords;
541 			}
542 		}
543 
544 		/*
545 		 * update dmap lsn
546 		 */
547 		if (lblkno == lastlblkno)
548 			continue;
549 
550 		lastlblkno = lblkno;
551 
552 		LOGSYNC_LOCK(log, flags);
553 		if (mp->lsn != 0) {
554 			/* inherit older/smaller lsn */
555 			logdiff(diffp, mp->lsn, log);
556 			if (difft < diffp) {
557 				mp->lsn = lsn;
558 
559 				/* move bp after tblock in logsync list */
560 				list_move(&mp->synclist, &tblk->synclist);
561 			}
562 
563 			/* inherit younger/larger clsn */
564 			logdiff(difft, tblk->clsn, log);
565 			logdiff(diffp, mp->clsn, log);
566 			if (difft > diffp)
567 				mp->clsn = tblk->clsn;
568 		} else {
569 			mp->log = log;
570 			mp->lsn = lsn;
571 
572 			/* insert bp after tblock in logsync list */
573 			log->count++;
574 			list_add(&mp->synclist, &tblk->synclist);
575 
576 			mp->clsn = tblk->clsn;
577 		}
578 		LOGSYNC_UNLOCK(log, flags);
579 	}
580 
581 	/* write the last buffer. */
582 	if (mp) {
583 		write_metapage(mp);
584 	}
585 
586 	return (0);
587 }
588 
589 
590 /*
591  * NAME:	dbNextAG()
592  *
593  * FUNCTION:	find the preferred allocation group for new allocations.
594  *
595  *		Within the allocation groups, we maintain a preferred
596  *		allocation group which consists of a group with at least
597  *		average free space.  It is the preferred group that we target
598  *		new inode allocation towards.  The tie-in between inode
599  *		allocation and block allocation occurs as we allocate the
600  *		first (data) block of an inode and specify the inode (block)
601  *		as the allocation hint for this block.
602  *
603  *		We try to avoid having more than one open file growing in
604  *		an allocation group, as this will lead to fragmentation.
605  *		This differs from the old OS/2 method of trying to keep
606  *		empty ags around for large allocations.
607  *
608  * PARAMETERS:
609  *	ipbmap	- pointer to in-core inode for the block map.
610  *
611  * RETURN VALUES:
612  *	the preferred allocation group number.
613  */
dbNextAG(struct inode * ipbmap)614 int dbNextAG(struct inode *ipbmap)
615 {
616 	s64 avgfree;
617 	int agpref;
618 	s64 hwm = 0;
619 	int i;
620 	int next_best = -1;
621 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
622 
623 	BMAP_LOCK(bmp);
624 
625 	/* determine the average number of free blocks within the ags. */
626 	avgfree = (u32)bmp->db_nfree / bmp->db_numag;
627 
628 	/*
629 	 * if the current preferred ag does not have an active allocator
630 	 * and has at least average freespace, return it
631 	 */
632 	agpref = bmp->db_agpref;
633 	if ((atomic_read(&bmp->db_active[agpref]) == 0) &&
634 	    (bmp->db_agfree[agpref] >= avgfree))
635 		goto unlock;
636 
637 	/* From the last preferred ag, find the next one with at least
638 	 * average free space.
639 	 */
640 	for (i = 0 ; i < bmp->db_numag; i++, agpref++) {
641 		if (agpref == bmp->db_numag)
642 			agpref = 0;
643 
644 		if (atomic_read(&bmp->db_active[agpref]))
645 			/* open file is currently growing in this ag */
646 			continue;
647 		if (bmp->db_agfree[agpref] >= avgfree) {
648 			/* Return this one */
649 			bmp->db_agpref = agpref;
650 			goto unlock;
651 		} else if (bmp->db_agfree[agpref] > hwm) {
652 			/* Less than avg. freespace, but best so far */
653 			hwm = bmp->db_agfree[agpref];
654 			next_best = agpref;
655 		}
656 	}
657 
658 	/*
659 	 * If no inactive ag was found with average freespace, use the
660 	 * next best
661 	 */
662 	if (next_best != -1)
663 		bmp->db_agpref = next_best;
664 	/* else leave db_agpref unchanged */
665 unlock:
666 	BMAP_UNLOCK(bmp);
667 
668 	/* return the preferred group.
669 	 */
670 	return (bmp->db_agpref);
671 }
672 
673 /*
674  * NAME:	dbAlloc()
675  *
676  * FUNCTION:	attempt to allocate a specified number of contiguous free
677  *		blocks from the working allocation block map.
678  *
679  *		the block allocation policy uses hints and a multi-step
680  *		approach.
681  *
682  *		for allocation requests smaller than the number of blocks
683  *		per dmap, we first try to allocate the new blocks
684  *		immediately following the hint.  if these blocks are not
685  *		available, we try to allocate blocks near the hint.  if
686  *		no blocks near the hint are available, we next try to
687  *		allocate within the same dmap as contains the hint.
688  *
689  *		if no blocks are available in the dmap or the allocation
690  *		request is larger than the dmap size, we try to allocate
691  *		within the same allocation group as contains the hint. if
692  *		this does not succeed, we finally try to allocate anywhere
693  *		within the aggregate.
694  *
695  *		we also try to allocate anywhere within the aggregate for
696  *		for allocation requests larger than the allocation group
697  *		size or requests that specify no hint value.
698  *
699  * PARAMETERS:
700  *	ip	- pointer to in-core inode;
701  *	hint	- allocation hint.
702  *	nblocks	- number of contiguous blocks in the range.
703  *	results	- on successful return, set to the starting block number
704  *		  of the newly allocated contiguous range.
705  *
706  * RETURN VALUES:
707  *	0	- success
708  *	-ENOSPC	- insufficient disk resources
709  *	-EIO	- i/o error
710  */
dbAlloc(struct inode * ip,s64 hint,s64 nblocks,s64 * results)711 int dbAlloc(struct inode *ip, s64 hint, s64 nblocks, s64 * results)
712 {
713 	int rc, agno;
714 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
715 	struct bmap *bmp;
716 	struct metapage *mp;
717 	s64 lblkno, blkno;
718 	struct dmap *dp;
719 	int l2nb;
720 	s64 mapSize;
721 	int writers;
722 
723 	/* assert that nblocks is valid */
724 	assert(nblocks > 0);
725 
726 	/* get the log2 number of blocks to be allocated.
727 	 * if the number of blocks is not a log2 multiple,
728 	 * it will be rounded up to the next log2 multiple.
729 	 */
730 	l2nb = BLKSTOL2(nblocks);
731 
732 	bmp = JFS_SBI(ip->i_sb)->bmap;
733 
734 	mapSize = bmp->db_mapsize;
735 
736 	/* the hint should be within the map */
737 	if (hint >= mapSize) {
738 		jfs_error(ip->i_sb, "the hint is outside the map\n");
739 		return -EIO;
740 	}
741 
742 	/* if the number of blocks to be allocated is greater than the
743 	 * allocation group size, try to allocate anywhere.
744 	 */
745 	if (l2nb > bmp->db_agl2size) {
746 		IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
747 
748 		rc = dbAllocAny(bmp, nblocks, l2nb, results);
749 
750 		goto write_unlock;
751 	}
752 
753 	/*
754 	 * If no hint, let dbNextAG recommend an allocation group
755 	 */
756 	if (hint == 0)
757 		goto pref_ag;
758 
759 	/* we would like to allocate close to the hint.  adjust the
760 	 * hint to the block following the hint since the allocators
761 	 * will start looking for free space starting at this point.
762 	 */
763 	blkno = hint + 1;
764 
765 	if (blkno >= bmp->db_mapsize)
766 		goto pref_ag;
767 
768 	agno = blkno >> bmp->db_agl2size;
769 
770 	/* check if blkno crosses over into a new allocation group.
771 	 * if so, check if we should allow allocations within this
772 	 * allocation group.
773 	 */
774 	if ((blkno & (bmp->db_agsize - 1)) == 0)
775 		/* check if the AG is currently being written to.
776 		 * if so, call dbNextAG() to find a non-busy
777 		 * AG with sufficient free space.
778 		 */
779 		if (atomic_read(&bmp->db_active[agno]))
780 			goto pref_ag;
781 
782 	/* check if the allocation request size can be satisfied from a
783 	 * single dmap.  if so, try to allocate from the dmap containing
784 	 * the hint using a tiered strategy.
785 	 */
786 	if (nblocks <= BPERDMAP) {
787 		IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
788 
789 		/* get the buffer for the dmap containing the hint.
790 		 */
791 		rc = -EIO;
792 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
793 		mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
794 		if (mp == NULL)
795 			goto read_unlock;
796 
797 		dp = (struct dmap *) mp->data;
798 
799 		/* first, try to satisfy the allocation request with the
800 		 * blocks beginning at the hint.
801 		 */
802 		if ((rc = dbAllocNext(bmp, dp, blkno, (int) nblocks))
803 		    != -ENOSPC) {
804 			if (rc == 0) {
805 				*results = blkno;
806 				mark_metapage_dirty(mp);
807 			}
808 
809 			release_metapage(mp);
810 			goto read_unlock;
811 		}
812 
813 		writers = atomic_read(&bmp->db_active[agno]);
814 		if ((writers > 1) ||
815 		    ((writers == 1) && (JFS_IP(ip)->active_ag != agno))) {
816 			/*
817 			 * Someone else is writing in this allocation
818 			 * group.  To avoid fragmenting, try another ag
819 			 */
820 			release_metapage(mp);
821 			IREAD_UNLOCK(ipbmap);
822 			goto pref_ag;
823 		}
824 
825 		/* next, try to satisfy the allocation request with blocks
826 		 * near the hint.
827 		 */
828 		if ((rc =
829 		     dbAllocNear(bmp, dp, blkno, (int) nblocks, l2nb, results))
830 		    != -ENOSPC) {
831 			if (rc == 0)
832 				mark_metapage_dirty(mp);
833 
834 			release_metapage(mp);
835 			goto read_unlock;
836 		}
837 
838 		/* try to satisfy the allocation request with blocks within
839 		 * the same dmap as the hint.
840 		 */
841 		if ((rc = dbAllocDmapLev(bmp, dp, (int) nblocks, l2nb, results))
842 		    != -ENOSPC) {
843 			if (rc == 0)
844 				mark_metapage_dirty(mp);
845 
846 			release_metapage(mp);
847 			goto read_unlock;
848 		}
849 
850 		release_metapage(mp);
851 		IREAD_UNLOCK(ipbmap);
852 	}
853 
854 	/* try to satisfy the allocation request with blocks within
855 	 * the same allocation group as the hint.
856 	 */
857 	IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
858 	if ((rc = dbAllocAG(bmp, agno, nblocks, l2nb, results)) != -ENOSPC)
859 		goto write_unlock;
860 
861 	IWRITE_UNLOCK(ipbmap);
862 
863 
864       pref_ag:
865 	/*
866 	 * Let dbNextAG recommend a preferred allocation group
867 	 */
868 	agno = dbNextAG(ipbmap);
869 	IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
870 
871 	/* Try to allocate within this allocation group.  if that fails, try to
872 	 * allocate anywhere in the map.
873 	 */
874 	if ((rc = dbAllocAG(bmp, agno, nblocks, l2nb, results)) == -ENOSPC)
875 		rc = dbAllocAny(bmp, nblocks, l2nb, results);
876 
877       write_unlock:
878 	IWRITE_UNLOCK(ipbmap);
879 
880 	return (rc);
881 
882       read_unlock:
883 	IREAD_UNLOCK(ipbmap);
884 
885 	return (rc);
886 }
887 
888 #ifdef _NOTYET
889 /*
890  * NAME:	dbAllocExact()
891  *
892  * FUNCTION:	try to allocate the requested extent;
893  *
894  * PARAMETERS:
895  *	ip	- pointer to in-core inode;
896  *	blkno	- extent address;
897  *	nblocks	- extent length;
898  *
899  * RETURN VALUES:
900  *	0	- success
901  *	-ENOSPC	- insufficient disk resources
902  *	-EIO	- i/o error
903  */
dbAllocExact(struct inode * ip,s64 blkno,int nblocks)904 int dbAllocExact(struct inode *ip, s64 blkno, int nblocks)
905 {
906 	int rc;
907 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
908 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
909 	struct dmap *dp;
910 	s64 lblkno;
911 	struct metapage *mp;
912 
913 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
914 
915 	/*
916 	 * validate extent request:
917 	 *
918 	 * note: defragfs policy:
919 	 *  max 64 blocks will be moved.
920 	 *  allocation request size must be satisfied from a single dmap.
921 	 */
922 	if (nblocks <= 0 || nblocks > BPERDMAP || blkno >= bmp->db_mapsize) {
923 		IREAD_UNLOCK(ipbmap);
924 		return -EINVAL;
925 	}
926 
927 	if (nblocks > ((s64) 1 << bmp->db_maxfreebud)) {
928 		/* the free space is no longer available */
929 		IREAD_UNLOCK(ipbmap);
930 		return -ENOSPC;
931 	}
932 
933 	/* read in the dmap covering the extent */
934 	lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
935 	mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
936 	if (mp == NULL) {
937 		IREAD_UNLOCK(ipbmap);
938 		return -EIO;
939 	}
940 	dp = (struct dmap *) mp->data;
941 
942 	/* try to allocate the requested extent */
943 	rc = dbAllocNext(bmp, dp, blkno, nblocks);
944 
945 	IREAD_UNLOCK(ipbmap);
946 
947 	if (rc == 0)
948 		mark_metapage_dirty(mp);
949 
950 	release_metapage(mp);
951 
952 	return (rc);
953 }
954 #endif /* _NOTYET */
955 
956 /*
957  * NAME:	dbReAlloc()
958  *
959  * FUNCTION:	attempt to extend a current allocation by a specified
960  *		number of blocks.
961  *
962  *		this routine attempts to satisfy the allocation request
963  *		by first trying to extend the existing allocation in
964  *		place by allocating the additional blocks as the blocks
965  *		immediately following the current allocation.  if these
966  *		blocks are not available, this routine will attempt to
967  *		allocate a new set of contiguous blocks large enough
968  *		to cover the existing allocation plus the additional
969  *		number of blocks required.
970  *
971  * PARAMETERS:
972  *	ip	    -  pointer to in-core inode requiring allocation.
973  *	blkno	    -  starting block of the current allocation.
974  *	nblocks	    -  number of contiguous blocks within the current
975  *		       allocation.
976  *	addnblocks  -  number of blocks to add to the allocation.
977  *	results	-      on successful return, set to the starting block number
978  *		       of the existing allocation if the existing allocation
979  *		       was extended in place or to a newly allocated contiguous
980  *		       range if the existing allocation could not be extended
981  *		       in place.
982  *
983  * RETURN VALUES:
984  *	0	- success
985  *	-ENOSPC	- insufficient disk resources
986  *	-EIO	- i/o error
987  */
988 int
dbReAlloc(struct inode * ip,s64 blkno,s64 nblocks,s64 addnblocks,s64 * results)989 dbReAlloc(struct inode *ip,
990 	  s64 blkno, s64 nblocks, s64 addnblocks, s64 * results)
991 {
992 	int rc;
993 
994 	/* try to extend the allocation in place.
995 	 */
996 	if ((rc = dbExtend(ip, blkno, nblocks, addnblocks)) == 0) {
997 		*results = blkno;
998 		return (0);
999 	} else {
1000 		if (rc != -ENOSPC)
1001 			return (rc);
1002 	}
1003 
1004 	/* could not extend the allocation in place, so allocate a
1005 	 * new set of blocks for the entire request (i.e. try to get
1006 	 * a range of contiguous blocks large enough to cover the
1007 	 * existing allocation plus the additional blocks.)
1008 	 */
1009 	return (dbAlloc
1010 		(ip, blkno + nblocks - 1, addnblocks + nblocks, results));
1011 }
1012 
1013 
1014 /*
1015  * NAME:	dbExtend()
1016  *
1017  * FUNCTION:	attempt to extend a current allocation by a specified
1018  *		number of blocks.
1019  *
1020  *		this routine attempts to satisfy the allocation request
1021  *		by first trying to extend the existing allocation in
1022  *		place by allocating the additional blocks as the blocks
1023  *		immediately following the current allocation.
1024  *
1025  * PARAMETERS:
1026  *	ip	    -  pointer to in-core inode requiring allocation.
1027  *	blkno	    -  starting block of the current allocation.
1028  *	nblocks	    -  number of contiguous blocks within the current
1029  *		       allocation.
1030  *	addnblocks  -  number of blocks to add to the allocation.
1031  *
1032  * RETURN VALUES:
1033  *	0	- success
1034  *	-ENOSPC	- insufficient disk resources
1035  *	-EIO	- i/o error
1036  */
dbExtend(struct inode * ip,s64 blkno,s64 nblocks,s64 addnblocks)1037 static int dbExtend(struct inode *ip, s64 blkno, s64 nblocks, s64 addnblocks)
1038 {
1039 	struct jfs_sb_info *sbi = JFS_SBI(ip->i_sb);
1040 	s64 lblkno, lastblkno, extblkno;
1041 	uint rel_block;
1042 	struct metapage *mp;
1043 	struct dmap *dp;
1044 	int rc;
1045 	struct inode *ipbmap = sbi->ipbmap;
1046 	struct bmap *bmp;
1047 
1048 	/*
1049 	 * We don't want a non-aligned extent to cross a page boundary
1050 	 */
1051 	if (((rel_block = blkno & (sbi->nbperpage - 1))) &&
1052 	    (rel_block + nblocks + addnblocks > sbi->nbperpage))
1053 		return -ENOSPC;
1054 
1055 	/* get the last block of the current allocation */
1056 	lastblkno = blkno + nblocks - 1;
1057 
1058 	/* determine the block number of the block following
1059 	 * the existing allocation.
1060 	 */
1061 	extblkno = lastblkno + 1;
1062 
1063 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
1064 
1065 	/* better be within the file system */
1066 	bmp = sbi->bmap;
1067 	if (lastblkno < 0 || lastblkno >= bmp->db_mapsize) {
1068 		IREAD_UNLOCK(ipbmap);
1069 		jfs_error(ip->i_sb, "the block is outside the filesystem\n");
1070 		return -EIO;
1071 	}
1072 
1073 	/* we'll attempt to extend the current allocation in place by
1074 	 * allocating the additional blocks as the blocks immediately
1075 	 * following the current allocation.  we only try to extend the
1076 	 * current allocation in place if the number of additional blocks
1077 	 * can fit into a dmap, the last block of the current allocation
1078 	 * is not the last block of the file system, and the start of the
1079 	 * inplace extension is not on an allocation group boundary.
1080 	 */
1081 	if (addnblocks > BPERDMAP || extblkno >= bmp->db_mapsize ||
1082 	    (extblkno & (bmp->db_agsize - 1)) == 0) {
1083 		IREAD_UNLOCK(ipbmap);
1084 		return -ENOSPC;
1085 	}
1086 
1087 	/* get the buffer for the dmap containing the first block
1088 	 * of the extension.
1089 	 */
1090 	lblkno = BLKTODMAP(extblkno, bmp->db_l2nbperpage);
1091 	mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
1092 	if (mp == NULL) {
1093 		IREAD_UNLOCK(ipbmap);
1094 		return -EIO;
1095 	}
1096 
1097 	dp = (struct dmap *) mp->data;
1098 
1099 	/* try to allocate the blocks immediately following the
1100 	 * current allocation.
1101 	 */
1102 	rc = dbAllocNext(bmp, dp, extblkno, (int) addnblocks);
1103 
1104 	IREAD_UNLOCK(ipbmap);
1105 
1106 	/* were we successful ? */
1107 	if (rc == 0)
1108 		write_metapage(mp);
1109 	else
1110 		/* we were not successful */
1111 		release_metapage(mp);
1112 
1113 	return (rc);
1114 }
1115 
1116 
1117 /*
1118  * NAME:	dbAllocNext()
1119  *
1120  * FUNCTION:	attempt to allocate the blocks of the specified block
1121  *		range within a dmap.
1122  *
1123  * PARAMETERS:
1124  *	bmp	-  pointer to bmap descriptor
1125  *	dp	-  pointer to dmap.
1126  *	blkno	-  starting block number of the range.
1127  *	nblocks	-  number of contiguous free blocks of the range.
1128  *
1129  * RETURN VALUES:
1130  *	0	- success
1131  *	-ENOSPC	- insufficient disk resources
1132  *	-EIO	- i/o error
1133  *
1134  * serialization: IREAD_LOCK(ipbmap) held on entry/exit;
1135  */
dbAllocNext(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)1136 static int dbAllocNext(struct bmap * bmp, struct dmap * dp, s64 blkno,
1137 		       int nblocks)
1138 {
1139 	int dbitno, word, rembits, nb, nwords, wbitno, nw;
1140 	int l2size;
1141 	s8 *leaf;
1142 	u32 mask;
1143 
1144 	if (dp->tree.leafidx != cpu_to_le32(LEAFIND)) {
1145 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmap page\n");
1146 		return -EIO;
1147 	}
1148 
1149 	/* pick up a pointer to the leaves of the dmap tree.
1150 	 */
1151 	leaf = dp->tree.stree + le32_to_cpu(dp->tree.leafidx);
1152 
1153 	/* determine the bit number and word within the dmap of the
1154 	 * starting block.
1155 	 */
1156 	dbitno = blkno & (BPERDMAP - 1);
1157 	word = dbitno >> L2DBWORD;
1158 
1159 	/* check if the specified block range is contained within
1160 	 * this dmap.
1161 	 */
1162 	if (dbitno + nblocks > BPERDMAP)
1163 		return -ENOSPC;
1164 
1165 	/* check if the starting leaf indicates that anything
1166 	 * is free.
1167 	 */
1168 	if (leaf[word] == NOFREE)
1169 		return -ENOSPC;
1170 
1171 	/* check the dmaps words corresponding to block range to see
1172 	 * if the block range is free.  not all bits of the first and
1173 	 * last words may be contained within the block range.  if this
1174 	 * is the case, we'll work against those words (i.e. partial first
1175 	 * and/or last) on an individual basis (a single pass) and examine
1176 	 * the actual bits to determine if they are free.  a single pass
1177 	 * will be used for all dmap words fully contained within the
1178 	 * specified range.  within this pass, the leaves of the dmap
1179 	 * tree will be examined to determine if the blocks are free. a
1180 	 * single leaf may describe the free space of multiple dmap
1181 	 * words, so we may visit only a subset of the actual leaves
1182 	 * corresponding to the dmap words of the block range.
1183 	 */
1184 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
1185 		/* determine the bit number within the word and
1186 		 * the number of bits within the word.
1187 		 */
1188 		wbitno = dbitno & (DBWORD - 1);
1189 		nb = min(rembits, DBWORD - wbitno);
1190 
1191 		/* check if only part of the word is to be examined.
1192 		 */
1193 		if (nb < DBWORD) {
1194 			/* check if the bits are free.
1195 			 */
1196 			mask = (ONES << (DBWORD - nb) >> wbitno);
1197 			if ((mask & ~le32_to_cpu(dp->wmap[word])) != mask)
1198 				return -ENOSPC;
1199 
1200 			word += 1;
1201 		} else {
1202 			/* one or more dmap words are fully contained
1203 			 * within the block range.  determine how many
1204 			 * words and how many bits.
1205 			 */
1206 			nwords = rembits >> L2DBWORD;
1207 			nb = nwords << L2DBWORD;
1208 
1209 			/* now examine the appropriate leaves to determine
1210 			 * if the blocks are free.
1211 			 */
1212 			while (nwords > 0) {
1213 				/* does the leaf describe any free space ?
1214 				 */
1215 				if (leaf[word] < BUDMIN)
1216 					return -ENOSPC;
1217 
1218 				/* determine the l2 number of bits provided
1219 				 * by this leaf.
1220 				 */
1221 				l2size =
1222 				    min_t(int, leaf[word], NLSTOL2BSZ(nwords));
1223 
1224 				/* determine how many words were handled.
1225 				 */
1226 				nw = BUDSIZE(l2size, BUDMIN);
1227 
1228 				nwords -= nw;
1229 				word += nw;
1230 			}
1231 		}
1232 	}
1233 
1234 	/* allocate the blocks.
1235 	 */
1236 	return (dbAllocDmap(bmp, dp, blkno, nblocks));
1237 }
1238 
1239 
1240 /*
1241  * NAME:	dbAllocNear()
1242  *
1243  * FUNCTION:	attempt to allocate a number of contiguous free blocks near
1244  *		a specified block (hint) within a dmap.
1245  *
1246  *		starting with the dmap leaf that covers the hint, we'll
1247  *		check the next four contiguous leaves for sufficient free
1248  *		space.  if sufficient free space is found, we'll allocate
1249  *		the desired free space.
1250  *
1251  * PARAMETERS:
1252  *	bmp	-  pointer to bmap descriptor
1253  *	dp	-  pointer to dmap.
1254  *	blkno	-  block number to allocate near.
1255  *	nblocks	-  actual number of contiguous free blocks desired.
1256  *	l2nb	-  log2 number of contiguous free blocks desired.
1257  *	results	-  on successful return, set to the starting block number
1258  *		   of the newly allocated range.
1259  *
1260  * RETURN VALUES:
1261  *	0	- success
1262  *	-ENOSPC	- insufficient disk resources
1263  *	-EIO	- i/o error
1264  *
1265  * serialization: IREAD_LOCK(ipbmap) held on entry/exit;
1266  */
1267 static int
dbAllocNear(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks,int l2nb,s64 * results)1268 dbAllocNear(struct bmap * bmp,
1269 	    struct dmap * dp, s64 blkno, int nblocks, int l2nb, s64 * results)
1270 {
1271 	int word, lword, rc;
1272 	s8 *leaf;
1273 
1274 	if (dp->tree.leafidx != cpu_to_le32(LEAFIND)) {
1275 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmap page\n");
1276 		return -EIO;
1277 	}
1278 
1279 	leaf = dp->tree.stree + le32_to_cpu(dp->tree.leafidx);
1280 
1281 	/* determine the word within the dmap that holds the hint
1282 	 * (i.e. blkno).  also, determine the last word in the dmap
1283 	 * that we'll include in our examination.
1284 	 */
1285 	word = (blkno & (BPERDMAP - 1)) >> L2DBWORD;
1286 	lword = min(word + 4, LPERDMAP);
1287 
1288 	/* examine the leaves for sufficient free space.
1289 	 */
1290 	for (; word < lword; word++) {
1291 		/* does the leaf describe sufficient free space ?
1292 		 */
1293 		if (leaf[word] < l2nb)
1294 			continue;
1295 
1296 		/* determine the block number within the file system
1297 		 * of the first block described by this dmap word.
1298 		 */
1299 		blkno = le64_to_cpu(dp->start) + (word << L2DBWORD);
1300 
1301 		/* if not all bits of the dmap word are free, get the
1302 		 * starting bit number within the dmap word of the required
1303 		 * string of free bits and adjust the block number with the
1304 		 * value.
1305 		 */
1306 		if (leaf[word] < BUDMIN)
1307 			blkno +=
1308 			    dbFindBits(le32_to_cpu(dp->wmap[word]), l2nb);
1309 
1310 		/* allocate the blocks.
1311 		 */
1312 		if ((rc = dbAllocDmap(bmp, dp, blkno, nblocks)) == 0)
1313 			*results = blkno;
1314 
1315 		return (rc);
1316 	}
1317 
1318 	return -ENOSPC;
1319 }
1320 
1321 
1322 /*
1323  * NAME:	dbAllocAG()
1324  *
1325  * FUNCTION:	attempt to allocate the specified number of contiguous
1326  *		free blocks within the specified allocation group.
1327  *
1328  *		unless the allocation group size is equal to the number
1329  *		of blocks per dmap, the dmap control pages will be used to
1330  *		find the required free space, if available.  we start the
1331  *		search at the highest dmap control page level which
1332  *		distinctly describes the allocation group's free space
1333  *		(i.e. the highest level at which the allocation group's
1334  *		free space is not mixed in with that of any other group).
1335  *		in addition, we start the search within this level at a
1336  *		height of the dmapctl dmtree at which the nodes distinctly
1337  *		describe the allocation group's free space.  at this height,
1338  *		the allocation group's free space may be represented by 1
1339  *		or two sub-trees, depending on the allocation group size.
1340  *		we search the top nodes of these subtrees left to right for
1341  *		sufficient free space.  if sufficient free space is found,
1342  *		the subtree is searched to find the leftmost leaf that
1343  *		has free space.  once we have made it to the leaf, we
1344  *		move the search to the next lower level dmap control page
1345  *		corresponding to this leaf.  we continue down the dmap control
1346  *		pages until we find the dmap that contains or starts the
1347  *		sufficient free space and we allocate at this dmap.
1348  *
1349  *		if the allocation group size is equal to the dmap size,
1350  *		we'll start at the dmap corresponding to the allocation
1351  *		group and attempt the allocation at this level.
1352  *
1353  *		the dmap control page search is also not performed if the
1354  *		allocation group is completely free and we go to the first
1355  *		dmap of the allocation group to do the allocation.  this is
1356  *		done because the allocation group may be part (not the first
1357  *		part) of a larger binary buddy system, causing the dmap
1358  *		control pages to indicate no free space (NOFREE) within
1359  *		the allocation group.
1360  *
1361  * PARAMETERS:
1362  *	bmp	-  pointer to bmap descriptor
1363  *	agno	- allocation group number.
1364  *	nblocks	-  actual number of contiguous free blocks desired.
1365  *	l2nb	-  log2 number of contiguous free blocks desired.
1366  *	results	-  on successful return, set to the starting block number
1367  *		   of the newly allocated range.
1368  *
1369  * RETURN VALUES:
1370  *	0	- success
1371  *	-ENOSPC	- insufficient disk resources
1372  *	-EIO	- i/o error
1373  *
1374  * note: IWRITE_LOCK(ipmap) held on entry/exit;
1375  */
1376 static int
dbAllocAG(struct bmap * bmp,int agno,s64 nblocks,int l2nb,s64 * results)1377 dbAllocAG(struct bmap * bmp, int agno, s64 nblocks, int l2nb, s64 * results)
1378 {
1379 	struct metapage *mp;
1380 	struct dmapctl *dcp;
1381 	int rc, ti, i, k, m, n, agperlev;
1382 	s64 blkno, lblkno;
1383 	int budmin;
1384 
1385 	/* allocation request should not be for more than the
1386 	 * allocation group size.
1387 	 */
1388 	if (l2nb > bmp->db_agl2size) {
1389 		jfs_error(bmp->db_ipbmap->i_sb,
1390 			  "allocation request is larger than the allocation group size\n");
1391 		return -EIO;
1392 	}
1393 
1394 	/* determine the starting block number of the allocation
1395 	 * group.
1396 	 */
1397 	blkno = (s64) agno << bmp->db_agl2size;
1398 
1399 	/* check if the allocation group size is the minimum allocation
1400 	 * group size or if the allocation group is completely free. if
1401 	 * the allocation group size is the minimum size of BPERDMAP (i.e.
1402 	 * 1 dmap), there is no need to search the dmap control page (below)
1403 	 * that fully describes the allocation group since the allocation
1404 	 * group is already fully described by a dmap.  in this case, we
1405 	 * just call dbAllocCtl() to search the dmap tree and allocate the
1406 	 * required space if available.
1407 	 *
1408 	 * if the allocation group is completely free, dbAllocCtl() is
1409 	 * also called to allocate the required space.  this is done for
1410 	 * two reasons.  first, it makes no sense searching the dmap control
1411 	 * pages for free space when we know that free space exists.  second,
1412 	 * the dmap control pages may indicate that the allocation group
1413 	 * has no free space if the allocation group is part (not the first
1414 	 * part) of a larger binary buddy system.
1415 	 */
1416 	if (bmp->db_agsize == BPERDMAP
1417 	    || bmp->db_agfree[agno] == bmp->db_agsize) {
1418 		rc = dbAllocCtl(bmp, nblocks, l2nb, blkno, results);
1419 		if ((rc == -ENOSPC) &&
1420 		    (bmp->db_agfree[agno] == bmp->db_agsize)) {
1421 			printk(KERN_ERR "blkno = %Lx, blocks = %Lx\n",
1422 			       (unsigned long long) blkno,
1423 			       (unsigned long long) nblocks);
1424 			jfs_error(bmp->db_ipbmap->i_sb,
1425 				  "dbAllocCtl failed in free AG\n");
1426 		}
1427 		return (rc);
1428 	}
1429 
1430 	/* the buffer for the dmap control page that fully describes the
1431 	 * allocation group.
1432 	 */
1433 	lblkno = BLKTOCTL(blkno, bmp->db_l2nbperpage, bmp->db_aglevel);
1434 	mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1435 	if (mp == NULL)
1436 		return -EIO;
1437 	dcp = (struct dmapctl *) mp->data;
1438 	budmin = dcp->budmin;
1439 
1440 	if (dcp->leafidx != cpu_to_le32(CTLLEAFIND)) {
1441 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmapctl page\n");
1442 		release_metapage(mp);
1443 		return -EIO;
1444 	}
1445 
1446 	/* search the subtree(s) of the dmap control page that describes
1447 	 * the allocation group, looking for sufficient free space.  to begin,
1448 	 * determine how many allocation groups are represented in a dmap
1449 	 * control page at the control page level (i.e. L0, L1, L2) that
1450 	 * fully describes an allocation group. next, determine the starting
1451 	 * tree index of this allocation group within the control page.
1452 	 */
1453 	agperlev =
1454 	    (1 << (L2LPERCTL - (bmp->db_agheight << 1))) / bmp->db_agwidth;
1455 	ti = bmp->db_agstart + bmp->db_agwidth * (agno & (agperlev - 1));
1456 
1457 	/* dmap control page trees fan-out by 4 and a single allocation
1458 	 * group may be described by 1 or 2 subtrees within the ag level
1459 	 * dmap control page, depending upon the ag size. examine the ag's
1460 	 * subtrees for sufficient free space, starting with the leftmost
1461 	 * subtree.
1462 	 */
1463 	for (i = 0; i < bmp->db_agwidth; i++, ti++) {
1464 		/* is there sufficient free space ?
1465 		 */
1466 		if (l2nb > dcp->stree[ti])
1467 			continue;
1468 
1469 		/* sufficient free space found in a subtree. now search down
1470 		 * the subtree to find the leftmost leaf that describes this
1471 		 * free space.
1472 		 */
1473 		for (k = bmp->db_agheight; k > 0; k--) {
1474 			for (n = 0, m = (ti << 2) + 1; n < 4; n++) {
1475 				if (l2nb <= dcp->stree[m + n]) {
1476 					ti = m + n;
1477 					break;
1478 				}
1479 			}
1480 			if (n == 4) {
1481 				jfs_error(bmp->db_ipbmap->i_sb,
1482 					  "failed descending stree\n");
1483 				release_metapage(mp);
1484 				return -EIO;
1485 			}
1486 		}
1487 
1488 		/* determine the block number within the file system
1489 		 * that corresponds to this leaf.
1490 		 */
1491 		if (bmp->db_aglevel == 2)
1492 			blkno = 0;
1493 		else if (bmp->db_aglevel == 1)
1494 			blkno &= ~(MAXL1SIZE - 1);
1495 		else		/* bmp->db_aglevel == 0 */
1496 			blkno &= ~(MAXL0SIZE - 1);
1497 
1498 		blkno +=
1499 		    ((s64) (ti - le32_to_cpu(dcp->leafidx))) << budmin;
1500 
1501 		/* release the buffer in preparation for going down
1502 		 * the next level of dmap control pages.
1503 		 */
1504 		release_metapage(mp);
1505 
1506 		/* check if we need to continue to search down the lower
1507 		 * level dmap control pages.  we need to if the number of
1508 		 * blocks required is less than maximum number of blocks
1509 		 * described at the next lower level.
1510 		 */
1511 		if (l2nb < budmin) {
1512 
1513 			/* search the lower level dmap control pages to get
1514 			 * the starting block number of the dmap that
1515 			 * contains or starts off the free space.
1516 			 */
1517 			if ((rc =
1518 			     dbFindCtl(bmp, l2nb, bmp->db_aglevel - 1,
1519 				       &blkno))) {
1520 				if (rc == -ENOSPC) {
1521 					jfs_error(bmp->db_ipbmap->i_sb,
1522 						  "control page inconsistent\n");
1523 					return -EIO;
1524 				}
1525 				return (rc);
1526 			}
1527 		}
1528 
1529 		/* allocate the blocks.
1530 		 */
1531 		rc = dbAllocCtl(bmp, nblocks, l2nb, blkno, results);
1532 		if (rc == -ENOSPC) {
1533 			jfs_error(bmp->db_ipbmap->i_sb,
1534 				  "unable to allocate blocks\n");
1535 			rc = -EIO;
1536 		}
1537 		return (rc);
1538 	}
1539 
1540 	/* no space in the allocation group.  release the buffer and
1541 	 * return -ENOSPC.
1542 	 */
1543 	release_metapage(mp);
1544 
1545 	return -ENOSPC;
1546 }
1547 
1548 
1549 /*
1550  * NAME:	dbAllocAny()
1551  *
1552  * FUNCTION:	attempt to allocate the specified number of contiguous
1553  *		free blocks anywhere in the file system.
1554  *
1555  *		dbAllocAny() attempts to find the sufficient free space by
1556  *		searching down the dmap control pages, starting with the
1557  *		highest level (i.e. L0, L1, L2) control page.  if free space
1558  *		large enough to satisfy the desired free space is found, the
1559  *		desired free space is allocated.
1560  *
1561  * PARAMETERS:
1562  *	bmp	-  pointer to bmap descriptor
1563  *	nblocks	 -  actual number of contiguous free blocks desired.
1564  *	l2nb	 -  log2 number of contiguous free blocks desired.
1565  *	results	-  on successful return, set to the starting block number
1566  *		   of the newly allocated range.
1567  *
1568  * RETURN VALUES:
1569  *	0	- success
1570  *	-ENOSPC	- insufficient disk resources
1571  *	-EIO	- i/o error
1572  *
1573  * serialization: IWRITE_LOCK(ipbmap) held on entry/exit;
1574  */
dbAllocAny(struct bmap * bmp,s64 nblocks,int l2nb,s64 * results)1575 static int dbAllocAny(struct bmap * bmp, s64 nblocks, int l2nb, s64 * results)
1576 {
1577 	int rc;
1578 	s64 blkno = 0;
1579 
1580 	/* starting with the top level dmap control page, search
1581 	 * down the dmap control levels for sufficient free space.
1582 	 * if free space is found, dbFindCtl() returns the starting
1583 	 * block number of the dmap that contains or starts off the
1584 	 * range of free space.
1585 	 */
1586 	if ((rc = dbFindCtl(bmp, l2nb, bmp->db_maxlevel, &blkno)))
1587 		return (rc);
1588 
1589 	/* allocate the blocks.
1590 	 */
1591 	rc = dbAllocCtl(bmp, nblocks, l2nb, blkno, results);
1592 	if (rc == -ENOSPC) {
1593 		jfs_error(bmp->db_ipbmap->i_sb, "unable to allocate blocks\n");
1594 		return -EIO;
1595 	}
1596 	return (rc);
1597 }
1598 
1599 
1600 /*
1601  * NAME:	dbDiscardAG()
1602  *
1603  * FUNCTION:	attempt to discard (TRIM) all free blocks of specific AG
1604  *
1605  *		algorithm:
1606  *		1) allocate blocks, as large as possible and save them
1607  *		   while holding IWRITE_LOCK on ipbmap
1608  *		2) trim all these saved block/length values
1609  *		3) mark the blocks free again
1610  *
1611  *		benefit:
1612  *		- we work only on one ag at some time, minimizing how long we
1613  *		  need to lock ipbmap
1614  *		- reading / writing the fs is possible most time, even on
1615  *		  trimming
1616  *
1617  *		downside:
1618  *		- we write two times to the dmapctl and dmap pages
1619  *		- but for me, this seems the best way, better ideas?
1620  *		/TR 2012
1621  *
1622  * PARAMETERS:
1623  *	ip	- pointer to in-core inode
1624  *	agno	- ag to trim
1625  *	minlen	- minimum value of contiguous blocks
1626  *
1627  * RETURN VALUES:
1628  *	s64	- actual number of blocks trimmed
1629  */
dbDiscardAG(struct inode * ip,int agno,s64 minlen)1630 s64 dbDiscardAG(struct inode *ip, int agno, s64 minlen)
1631 {
1632 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
1633 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
1634 	s64 nblocks, blkno;
1635 	u64 trimmed = 0;
1636 	int rc, l2nb;
1637 	struct super_block *sb = ipbmap->i_sb;
1638 
1639 	struct range2trim {
1640 		u64 blkno;
1641 		u64 nblocks;
1642 	} *totrim, *tt;
1643 
1644 	/* max blkno / nblocks pairs to trim */
1645 	int count = 0, range_cnt;
1646 	u64 max_ranges;
1647 
1648 	/* prevent others from writing new stuff here, while trimming */
1649 	IWRITE_LOCK(ipbmap, RDWRLOCK_DMAP);
1650 
1651 	nblocks = bmp->db_agfree[agno];
1652 	max_ranges = nblocks;
1653 	do_div(max_ranges, minlen);
1654 	range_cnt = min_t(u64, max_ranges + 1, 32 * 1024);
1655 	totrim = kmalloc_array(range_cnt, sizeof(struct range2trim), GFP_NOFS);
1656 	if (totrim == NULL) {
1657 		jfs_error(bmp->db_ipbmap->i_sb, "no memory for trim array\n");
1658 		IWRITE_UNLOCK(ipbmap);
1659 		return 0;
1660 	}
1661 
1662 	tt = totrim;
1663 	while (nblocks >= minlen) {
1664 		l2nb = BLKSTOL2(nblocks);
1665 
1666 		/* 0 = okay, -EIO = fatal, -ENOSPC -> try smaller block */
1667 		rc = dbAllocAG(bmp, agno, nblocks, l2nb, &blkno);
1668 		if (rc == 0) {
1669 			tt->blkno = blkno;
1670 			tt->nblocks = nblocks;
1671 			tt++; count++;
1672 
1673 			/* the whole ag is free, trim now */
1674 			if (bmp->db_agfree[agno] == 0)
1675 				break;
1676 
1677 			/* give a hint for the next while */
1678 			nblocks = bmp->db_agfree[agno];
1679 			continue;
1680 		} else if (rc == -ENOSPC) {
1681 			/* search for next smaller log2 block */
1682 			l2nb = BLKSTOL2(nblocks) - 1;
1683 			nblocks = 1LL << l2nb;
1684 		} else {
1685 			/* Trim any already allocated blocks */
1686 			jfs_error(bmp->db_ipbmap->i_sb, "-EIO\n");
1687 			break;
1688 		}
1689 
1690 		/* check, if our trim array is full */
1691 		if (unlikely(count >= range_cnt - 1))
1692 			break;
1693 	}
1694 	IWRITE_UNLOCK(ipbmap);
1695 
1696 	tt->nblocks = 0; /* mark the current end */
1697 	for (tt = totrim; tt->nblocks != 0; tt++) {
1698 		/* when mounted with online discard, dbFree() will
1699 		 * call jfs_issue_discard() itself */
1700 		if (!(JFS_SBI(sb)->flag & JFS_DISCARD))
1701 			jfs_issue_discard(ip, tt->blkno, tt->nblocks);
1702 		dbFree(ip, tt->blkno, tt->nblocks);
1703 		trimmed += tt->nblocks;
1704 	}
1705 	kfree(totrim);
1706 
1707 	return trimmed;
1708 }
1709 
1710 /*
1711  * NAME:	dbFindCtl()
1712  *
1713  * FUNCTION:	starting at a specified dmap control page level and block
1714  *		number, search down the dmap control levels for a range of
1715  *		contiguous free blocks large enough to satisfy an allocation
1716  *		request for the specified number of free blocks.
1717  *
1718  *		if sufficient contiguous free blocks are found, this routine
1719  *		returns the starting block number within a dmap page that
1720  *		contains or starts a range of contiqious free blocks that
1721  *		is sufficient in size.
1722  *
1723  * PARAMETERS:
1724  *	bmp	-  pointer to bmap descriptor
1725  *	level	-  starting dmap control page level.
1726  *	l2nb	-  log2 number of contiguous free blocks desired.
1727  *	*blkno	-  on entry, starting block number for conducting the search.
1728  *		   on successful return, the first block within a dmap page
1729  *		   that contains or starts a range of contiguous free blocks.
1730  *
1731  * RETURN VALUES:
1732  *	0	- success
1733  *	-ENOSPC	- insufficient disk resources
1734  *	-EIO	- i/o error
1735  *
1736  * serialization: IWRITE_LOCK(ipbmap) held on entry/exit;
1737  */
dbFindCtl(struct bmap * bmp,int l2nb,int level,s64 * blkno)1738 static int dbFindCtl(struct bmap * bmp, int l2nb, int level, s64 * blkno)
1739 {
1740 	int rc, leafidx, lev;
1741 	s64 b, lblkno;
1742 	struct dmapctl *dcp;
1743 	int budmin;
1744 	struct metapage *mp;
1745 
1746 	/* starting at the specified dmap control page level and block
1747 	 * number, search down the dmap control levels for the starting
1748 	 * block number of a dmap page that contains or starts off
1749 	 * sufficient free blocks.
1750 	 */
1751 	for (lev = level, b = *blkno; lev >= 0; lev--) {
1752 		/* get the buffer of the dmap control page for the block
1753 		 * number and level (i.e. L0, L1, L2).
1754 		 */
1755 		lblkno = BLKTOCTL(b, bmp->db_l2nbperpage, lev);
1756 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1757 		if (mp == NULL)
1758 			return -EIO;
1759 		dcp = (struct dmapctl *) mp->data;
1760 		budmin = dcp->budmin;
1761 
1762 		if (dcp->leafidx != cpu_to_le32(CTLLEAFIND)) {
1763 			jfs_error(bmp->db_ipbmap->i_sb,
1764 				  "Corrupt dmapctl page\n");
1765 			release_metapage(mp);
1766 			return -EIO;
1767 		}
1768 
1769 		/* search the tree within the dmap control page for
1770 		 * sufficient free space.  if sufficient free space is found,
1771 		 * dbFindLeaf() returns the index of the leaf at which
1772 		 * free space was found.
1773 		 */
1774 		rc = dbFindLeaf((dmtree_t *) dcp, l2nb, &leafidx);
1775 
1776 		/* release the buffer.
1777 		 */
1778 		release_metapage(mp);
1779 
1780 		/* space found ?
1781 		 */
1782 		if (rc) {
1783 			if (lev != level) {
1784 				jfs_error(bmp->db_ipbmap->i_sb,
1785 					  "dmap inconsistent\n");
1786 				return -EIO;
1787 			}
1788 			return -ENOSPC;
1789 		}
1790 
1791 		/* adjust the block number to reflect the location within
1792 		 * the dmap control page (i.e. the leaf) at which free
1793 		 * space was found.
1794 		 */
1795 		b += (((s64) leafidx) << budmin);
1796 
1797 		/* we stop the search at this dmap control page level if
1798 		 * the number of blocks required is greater than or equal
1799 		 * to the maximum number of blocks described at the next
1800 		 * (lower) level.
1801 		 */
1802 		if (l2nb >= budmin)
1803 			break;
1804 	}
1805 
1806 	*blkno = b;
1807 	return (0);
1808 }
1809 
1810 
1811 /*
1812  * NAME:	dbAllocCtl()
1813  *
1814  * FUNCTION:	attempt to allocate a specified number of contiguous
1815  *		blocks starting within a specific dmap.
1816  *
1817  *		this routine is called by higher level routines that search
1818  *		the dmap control pages above the actual dmaps for contiguous
1819  *		free space.  the result of successful searches by these
1820  *		routines are the starting block numbers within dmaps, with
1821  *		the dmaps themselves containing the desired contiguous free
1822  *		space or starting a contiguous free space of desired size
1823  *		that is made up of the blocks of one or more dmaps. these
1824  *		calls should not fail due to insufficent resources.
1825  *
1826  *		this routine is called in some cases where it is not known
1827  *		whether it will fail due to insufficient resources.  more
1828  *		specifically, this occurs when allocating from an allocation
1829  *		group whose size is equal to the number of blocks per dmap.
1830  *		in this case, the dmap control pages are not examined prior
1831  *		to calling this routine (to save pathlength) and the call
1832  *		might fail.
1833  *
1834  *		for a request size that fits within a dmap, this routine relies
1835  *		upon the dmap's dmtree to find the requested contiguous free
1836  *		space.  for request sizes that are larger than a dmap, the
1837  *		requested free space will start at the first block of the
1838  *		first dmap (i.e. blkno).
1839  *
1840  * PARAMETERS:
1841  *	bmp	-  pointer to bmap descriptor
1842  *	nblocks	 -  actual number of contiguous free blocks to allocate.
1843  *	l2nb	 -  log2 number of contiguous free blocks to allocate.
1844  *	blkno	 -  starting block number of the dmap to start the allocation
1845  *		    from.
1846  *	results	-  on successful return, set to the starting block number
1847  *		   of the newly allocated range.
1848  *
1849  * RETURN VALUES:
1850  *	0	- success
1851  *	-ENOSPC	- insufficient disk resources
1852  *	-EIO	- i/o error
1853  *
1854  * serialization: IWRITE_LOCK(ipbmap) held on entry/exit;
1855  */
1856 static int
dbAllocCtl(struct bmap * bmp,s64 nblocks,int l2nb,s64 blkno,s64 * results)1857 dbAllocCtl(struct bmap * bmp, s64 nblocks, int l2nb, s64 blkno, s64 * results)
1858 {
1859 	int rc, nb;
1860 	s64 b, lblkno, n;
1861 	struct metapage *mp;
1862 	struct dmap *dp;
1863 
1864 	/* check if the allocation request is confined to a single dmap.
1865 	 */
1866 	if (l2nb <= L2BPERDMAP) {
1867 		/* get the buffer for the dmap.
1868 		 */
1869 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
1870 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1871 		if (mp == NULL)
1872 			return -EIO;
1873 		dp = (struct dmap *) mp->data;
1874 
1875 		/* try to allocate the blocks.
1876 		 */
1877 		rc = dbAllocDmapLev(bmp, dp, (int) nblocks, l2nb, results);
1878 		if (rc == 0)
1879 			mark_metapage_dirty(mp);
1880 
1881 		release_metapage(mp);
1882 
1883 		return (rc);
1884 	}
1885 
1886 	/* allocation request involving multiple dmaps. it must start on
1887 	 * a dmap boundary.
1888 	 */
1889 	assert((blkno & (BPERDMAP - 1)) == 0);
1890 
1891 	/* allocate the blocks dmap by dmap.
1892 	 */
1893 	for (n = nblocks, b = blkno; n > 0; n -= nb, b += nb) {
1894 		/* get the buffer for the dmap.
1895 		 */
1896 		lblkno = BLKTODMAP(b, bmp->db_l2nbperpage);
1897 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1898 		if (mp == NULL) {
1899 			rc = -EIO;
1900 			goto backout;
1901 		}
1902 		dp = (struct dmap *) mp->data;
1903 
1904 		/* the dmap better be all free.
1905 		 */
1906 		if (dp->tree.stree[ROOT] != L2BPERDMAP) {
1907 			release_metapage(mp);
1908 			jfs_error(bmp->db_ipbmap->i_sb,
1909 				  "the dmap is not all free\n");
1910 			rc = -EIO;
1911 			goto backout;
1912 		}
1913 
1914 		/* determine how many blocks to allocate from this dmap.
1915 		 */
1916 		nb = min_t(s64, n, BPERDMAP);
1917 
1918 		/* allocate the blocks from the dmap.
1919 		 */
1920 		if ((rc = dbAllocDmap(bmp, dp, b, nb))) {
1921 			release_metapage(mp);
1922 			goto backout;
1923 		}
1924 
1925 		/* write the buffer.
1926 		 */
1927 		write_metapage(mp);
1928 	}
1929 
1930 	/* set the results (starting block number) and return.
1931 	 */
1932 	*results = blkno;
1933 	return (0);
1934 
1935 	/* something failed in handling an allocation request involving
1936 	 * multiple dmaps.  we'll try to clean up by backing out any
1937 	 * allocation that has already happened for this request.  if
1938 	 * we fail in backing out the allocation, we'll mark the file
1939 	 * system to indicate that blocks have been leaked.
1940 	 */
1941       backout:
1942 
1943 	/* try to backout the allocations dmap by dmap.
1944 	 */
1945 	for (n = nblocks - n, b = blkno; n > 0;
1946 	     n -= BPERDMAP, b += BPERDMAP) {
1947 		/* get the buffer for this dmap.
1948 		 */
1949 		lblkno = BLKTODMAP(b, bmp->db_l2nbperpage);
1950 		mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
1951 		if (mp == NULL) {
1952 			/* could not back out.  mark the file system
1953 			 * to indicate that we have leaked blocks.
1954 			 */
1955 			jfs_error(bmp->db_ipbmap->i_sb,
1956 				  "I/O Error: Block Leakage\n");
1957 			continue;
1958 		}
1959 		dp = (struct dmap *) mp->data;
1960 
1961 		/* free the blocks is this dmap.
1962 		 */
1963 		if (dbFreeDmap(bmp, dp, b, BPERDMAP)) {
1964 			/* could not back out.  mark the file system
1965 			 * to indicate that we have leaked blocks.
1966 			 */
1967 			release_metapage(mp);
1968 			jfs_error(bmp->db_ipbmap->i_sb, "Block Leakage\n");
1969 			continue;
1970 		}
1971 
1972 		/* write the buffer.
1973 		 */
1974 		write_metapage(mp);
1975 	}
1976 
1977 	return (rc);
1978 }
1979 
1980 
1981 /*
1982  * NAME:	dbAllocDmapLev()
1983  *
1984  * FUNCTION:	attempt to allocate a specified number of contiguous blocks
1985  *		from a specified dmap.
1986  *
1987  *		this routine checks if the contiguous blocks are available.
1988  *		if so, nblocks of blocks are allocated; otherwise, ENOSPC is
1989  *		returned.
1990  *
1991  * PARAMETERS:
1992  *	mp	-  pointer to bmap descriptor
1993  *	dp	-  pointer to dmap to attempt to allocate blocks from.
1994  *	l2nb	-  log2 number of contiguous block desired.
1995  *	nblocks	-  actual number of contiguous block desired.
1996  *	results	-  on successful return, set to the starting block number
1997  *		   of the newly allocated range.
1998  *
1999  * RETURN VALUES:
2000  *	0	- success
2001  *	-ENOSPC	- insufficient disk resources
2002  *	-EIO	- i/o error
2003  *
2004  * serialization: IREAD_LOCK(ipbmap), e.g., from dbAlloc(), or
2005  *	IWRITE_LOCK(ipbmap), e.g., dbAllocCtl(), held on entry/exit;
2006  */
2007 static int
dbAllocDmapLev(struct bmap * bmp,struct dmap * dp,int nblocks,int l2nb,s64 * results)2008 dbAllocDmapLev(struct bmap * bmp,
2009 	       struct dmap * dp, int nblocks, int l2nb, s64 * results)
2010 {
2011 	s64 blkno;
2012 	int leafidx, rc;
2013 
2014 	/* can't be more than a dmaps worth of blocks */
2015 	assert(l2nb <= L2BPERDMAP);
2016 
2017 	/* search the tree within the dmap page for sufficient
2018 	 * free space.  if sufficient free space is found, dbFindLeaf()
2019 	 * returns the index of the leaf at which free space was found.
2020 	 */
2021 	if (dbFindLeaf((dmtree_t *) & dp->tree, l2nb, &leafidx))
2022 		return -ENOSPC;
2023 
2024 	/* determine the block number within the file system corresponding
2025 	 * to the leaf at which free space was found.
2026 	 */
2027 	blkno = le64_to_cpu(dp->start) + (leafidx << L2DBWORD);
2028 
2029 	/* if not all bits of the dmap word are free, get the starting
2030 	 * bit number within the dmap word of the required string of free
2031 	 * bits and adjust the block number with this value.
2032 	 */
2033 	if (dp->tree.stree[leafidx + LEAFIND] < BUDMIN)
2034 		blkno += dbFindBits(le32_to_cpu(dp->wmap[leafidx]), l2nb);
2035 
2036 	/* allocate the blocks */
2037 	if ((rc = dbAllocDmap(bmp, dp, blkno, nblocks)) == 0)
2038 		*results = blkno;
2039 
2040 	return (rc);
2041 }
2042 
2043 
2044 /*
2045  * NAME:	dbAllocDmap()
2046  *
2047  * FUNCTION:	adjust the disk allocation map to reflect the allocation
2048  *		of a specified block range within a dmap.
2049  *
2050  *		this routine allocates the specified blocks from the dmap
2051  *		through a call to dbAllocBits(). if the allocation of the
2052  *		block range causes the maximum string of free blocks within
2053  *		the dmap to change (i.e. the value of the root of the dmap's
2054  *		dmtree), this routine will cause this change to be reflected
2055  *		up through the appropriate levels of the dmap control pages
2056  *		by a call to dbAdjCtl() for the L0 dmap control page that
2057  *		covers this dmap.
2058  *
2059  * PARAMETERS:
2060  *	bmp	-  pointer to bmap descriptor
2061  *	dp	-  pointer to dmap to allocate the block range from.
2062  *	blkno	-  starting block number of the block to be allocated.
2063  *	nblocks	-  number of blocks to be allocated.
2064  *
2065  * RETURN VALUES:
2066  *	0	- success
2067  *	-EIO	- i/o error
2068  *
2069  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2070  */
dbAllocDmap(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2071 static int dbAllocDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
2072 		       int nblocks)
2073 {
2074 	s8 oldroot;
2075 	int rc;
2076 
2077 	/* save the current value of the root (i.e. maximum free string)
2078 	 * of the dmap tree.
2079 	 */
2080 	oldroot = dp->tree.stree[ROOT];
2081 
2082 	/* allocate the specified (blocks) bits */
2083 	dbAllocBits(bmp, dp, blkno, nblocks);
2084 
2085 	/* if the root has not changed, done. */
2086 	if (dp->tree.stree[ROOT] == oldroot)
2087 		return (0);
2088 
2089 	/* root changed. bubble the change up to the dmap control pages.
2090 	 * if the adjustment of the upper level control pages fails,
2091 	 * backout the bit allocation (thus making everything consistent).
2092 	 */
2093 	if ((rc = dbAdjCtl(bmp, blkno, dp->tree.stree[ROOT], 1, 0)))
2094 		dbFreeBits(bmp, dp, blkno, nblocks);
2095 
2096 	return (rc);
2097 }
2098 
2099 
2100 /*
2101  * NAME:	dbFreeDmap()
2102  *
2103  * FUNCTION:	adjust the disk allocation map to reflect the allocation
2104  *		of a specified block range within a dmap.
2105  *
2106  *		this routine frees the specified blocks from the dmap through
2107  *		a call to dbFreeBits(). if the deallocation of the block range
2108  *		causes the maximum string of free blocks within the dmap to
2109  *		change (i.e. the value of the root of the dmap's dmtree), this
2110  *		routine will cause this change to be reflected up through the
2111  *		appropriate levels of the dmap control pages by a call to
2112  *		dbAdjCtl() for the L0 dmap control page that covers this dmap.
2113  *
2114  * PARAMETERS:
2115  *	bmp	-  pointer to bmap descriptor
2116  *	dp	-  pointer to dmap to free the block range from.
2117  *	blkno	-  starting block number of the block to be freed.
2118  *	nblocks	-  number of blocks to be freed.
2119  *
2120  * RETURN VALUES:
2121  *	0	- success
2122  *	-EIO	- i/o error
2123  *
2124  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2125  */
dbFreeDmap(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2126 static int dbFreeDmap(struct bmap * bmp, struct dmap * dp, s64 blkno,
2127 		      int nblocks)
2128 {
2129 	s8 oldroot;
2130 	int rc = 0, word;
2131 
2132 	/* save the current value of the root (i.e. maximum free string)
2133 	 * of the dmap tree.
2134 	 */
2135 	oldroot = dp->tree.stree[ROOT];
2136 
2137 	/* free the specified (blocks) bits */
2138 	rc = dbFreeBits(bmp, dp, blkno, nblocks);
2139 
2140 	/* if error or the root has not changed, done. */
2141 	if (rc || (dp->tree.stree[ROOT] == oldroot))
2142 		return (rc);
2143 
2144 	/* root changed. bubble the change up to the dmap control pages.
2145 	 * if the adjustment of the upper level control pages fails,
2146 	 * backout the deallocation.
2147 	 */
2148 	if ((rc = dbAdjCtl(bmp, blkno, dp->tree.stree[ROOT], 0, 0))) {
2149 		word = (blkno & (BPERDMAP - 1)) >> L2DBWORD;
2150 
2151 		/* as part of backing out the deallocation, we will have
2152 		 * to back split the dmap tree if the deallocation caused
2153 		 * the freed blocks to become part of a larger binary buddy
2154 		 * system.
2155 		 */
2156 		if (dp->tree.stree[word] == NOFREE)
2157 			dbBackSplit((dmtree_t *) & dp->tree, word);
2158 
2159 		dbAllocBits(bmp, dp, blkno, nblocks);
2160 	}
2161 
2162 	return (rc);
2163 }
2164 
2165 
2166 /*
2167  * NAME:	dbAllocBits()
2168  *
2169  * FUNCTION:	allocate a specified block range from a dmap.
2170  *
2171  *		this routine updates the dmap to reflect the working
2172  *		state allocation of the specified block range. it directly
2173  *		updates the bits of the working map and causes the adjustment
2174  *		of the binary buddy system described by the dmap's dmtree
2175  *		leaves to reflect the bits allocated.  it also causes the
2176  *		dmap's dmtree, as a whole, to reflect the allocated range.
2177  *
2178  * PARAMETERS:
2179  *	bmp	-  pointer to bmap descriptor
2180  *	dp	-  pointer to dmap to allocate bits from.
2181  *	blkno	-  starting block number of the bits to be allocated.
2182  *	nblocks	-  number of bits to be allocated.
2183  *
2184  * RETURN VALUES: none
2185  *
2186  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2187  */
dbAllocBits(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2188 static void dbAllocBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
2189 			int nblocks)
2190 {
2191 	int dbitno, word, rembits, nb, nwords, wbitno, nw, agno;
2192 	dmtree_t *tp = (dmtree_t *) & dp->tree;
2193 	int size;
2194 	s8 *leaf;
2195 
2196 	/* pick up a pointer to the leaves of the dmap tree */
2197 	leaf = dp->tree.stree + LEAFIND;
2198 
2199 	/* determine the bit number and word within the dmap of the
2200 	 * starting block.
2201 	 */
2202 	dbitno = blkno & (BPERDMAP - 1);
2203 	word = dbitno >> L2DBWORD;
2204 
2205 	/* block range better be within the dmap */
2206 	assert(dbitno + nblocks <= BPERDMAP);
2207 
2208 	/* allocate the bits of the dmap's words corresponding to the block
2209 	 * range. not all bits of the first and last words may be contained
2210 	 * within the block range.  if this is the case, we'll work against
2211 	 * those words (i.e. partial first and/or last) on an individual basis
2212 	 * (a single pass), allocating the bits of interest by hand and
2213 	 * updating the leaf corresponding to the dmap word. a single pass
2214 	 * will be used for all dmap words fully contained within the
2215 	 * specified range.  within this pass, the bits of all fully contained
2216 	 * dmap words will be marked as free in a single shot and the leaves
2217 	 * will be updated. a single leaf may describe the free space of
2218 	 * multiple dmap words, so we may update only a subset of the actual
2219 	 * leaves corresponding to the dmap words of the block range.
2220 	 */
2221 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
2222 		/* determine the bit number within the word and
2223 		 * the number of bits within the word.
2224 		 */
2225 		wbitno = dbitno & (DBWORD - 1);
2226 		nb = min(rembits, DBWORD - wbitno);
2227 
2228 		/* check if only part of a word is to be allocated.
2229 		 */
2230 		if (nb < DBWORD) {
2231 			/* allocate (set to 1) the appropriate bits within
2232 			 * this dmap word.
2233 			 */
2234 			dp->wmap[word] |= cpu_to_le32(ONES << (DBWORD - nb)
2235 						      >> wbitno);
2236 
2237 			/* update the leaf for this dmap word. in addition
2238 			 * to setting the leaf value to the binary buddy max
2239 			 * of the updated dmap word, dbSplit() will split
2240 			 * the binary system of the leaves if need be.
2241 			 */
2242 			dbSplit(tp, word, BUDMIN,
2243 				dbMaxBud((u8 *) & dp->wmap[word]));
2244 
2245 			word += 1;
2246 		} else {
2247 			/* one or more dmap words are fully contained
2248 			 * within the block range.  determine how many
2249 			 * words and allocate (set to 1) the bits of these
2250 			 * words.
2251 			 */
2252 			nwords = rembits >> L2DBWORD;
2253 			memset(&dp->wmap[word], (int) ONES, nwords * 4);
2254 
2255 			/* determine how many bits.
2256 			 */
2257 			nb = nwords << L2DBWORD;
2258 
2259 			/* now update the appropriate leaves to reflect
2260 			 * the allocated words.
2261 			 */
2262 			for (; nwords > 0; nwords -= nw) {
2263 				if (leaf[word] < BUDMIN) {
2264 					jfs_error(bmp->db_ipbmap->i_sb,
2265 						  "leaf page corrupt\n");
2266 					break;
2267 				}
2268 
2269 				/* determine what the leaf value should be
2270 				 * updated to as the minimum of the l2 number
2271 				 * of bits being allocated and the l2 number
2272 				 * of bits currently described by this leaf.
2273 				 */
2274 				size = min_t(int, leaf[word],
2275 					     NLSTOL2BSZ(nwords));
2276 
2277 				/* update the leaf to reflect the allocation.
2278 				 * in addition to setting the leaf value to
2279 				 * NOFREE, dbSplit() will split the binary
2280 				 * system of the leaves to reflect the current
2281 				 * allocation (size).
2282 				 */
2283 				dbSplit(tp, word, size, NOFREE);
2284 
2285 				/* get the number of dmap words handled */
2286 				nw = BUDSIZE(size, BUDMIN);
2287 				word += nw;
2288 			}
2289 		}
2290 	}
2291 
2292 	/* update the free count for this dmap */
2293 	le32_add_cpu(&dp->nfree, -nblocks);
2294 
2295 	BMAP_LOCK(bmp);
2296 
2297 	/* if this allocation group is completely free,
2298 	 * update the maximum allocation group number if this allocation
2299 	 * group is the new max.
2300 	 */
2301 	agno = blkno >> bmp->db_agl2size;
2302 	if (agno > bmp->db_maxag)
2303 		bmp->db_maxag = agno;
2304 
2305 	/* update the free count for the allocation group and map */
2306 	bmp->db_agfree[agno] -= nblocks;
2307 	bmp->db_nfree -= nblocks;
2308 
2309 	BMAP_UNLOCK(bmp);
2310 }
2311 
2312 
2313 /*
2314  * NAME:	dbFreeBits()
2315  *
2316  * FUNCTION:	free a specified block range from a dmap.
2317  *
2318  *		this routine updates the dmap to reflect the working
2319  *		state allocation of the specified block range. it directly
2320  *		updates the bits of the working map and causes the adjustment
2321  *		of the binary buddy system described by the dmap's dmtree
2322  *		leaves to reflect the bits freed.  it also causes the dmap's
2323  *		dmtree, as a whole, to reflect the deallocated range.
2324  *
2325  * PARAMETERS:
2326  *	bmp	-  pointer to bmap descriptor
2327  *	dp	-  pointer to dmap to free bits from.
2328  *	blkno	-  starting block number of the bits to be freed.
2329  *	nblocks	-  number of bits to be freed.
2330  *
2331  * RETURN VALUES: 0 for success
2332  *
2333  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2334  */
dbFreeBits(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)2335 static int dbFreeBits(struct bmap * bmp, struct dmap * dp, s64 blkno,
2336 		       int nblocks)
2337 {
2338 	int dbitno, word, rembits, nb, nwords, wbitno, nw, agno;
2339 	dmtree_t *tp = (dmtree_t *) & dp->tree;
2340 	int rc = 0;
2341 	int size;
2342 
2343 	/* determine the bit number and word within the dmap of the
2344 	 * starting block.
2345 	 */
2346 	dbitno = blkno & (BPERDMAP - 1);
2347 	word = dbitno >> L2DBWORD;
2348 
2349 	/* block range better be within the dmap.
2350 	 */
2351 	assert(dbitno + nblocks <= BPERDMAP);
2352 
2353 	/* free the bits of the dmaps words corresponding to the block range.
2354 	 * not all bits of the first and last words may be contained within
2355 	 * the block range.  if this is the case, we'll work against those
2356 	 * words (i.e. partial first and/or last) on an individual basis
2357 	 * (a single pass), freeing the bits of interest by hand and updating
2358 	 * the leaf corresponding to the dmap word. a single pass will be used
2359 	 * for all dmap words fully contained within the specified range.
2360 	 * within this pass, the bits of all fully contained dmap words will
2361 	 * be marked as free in a single shot and the leaves will be updated. a
2362 	 * single leaf may describe the free space of multiple dmap words,
2363 	 * so we may update only a subset of the actual leaves corresponding
2364 	 * to the dmap words of the block range.
2365 	 *
2366 	 * dbJoin() is used to update leaf values and will join the binary
2367 	 * buddy system of the leaves if the new leaf values indicate this
2368 	 * should be done.
2369 	 */
2370 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
2371 		/* determine the bit number within the word and
2372 		 * the number of bits within the word.
2373 		 */
2374 		wbitno = dbitno & (DBWORD - 1);
2375 		nb = min(rembits, DBWORD - wbitno);
2376 
2377 		/* check if only part of a word is to be freed.
2378 		 */
2379 		if (nb < DBWORD) {
2380 			/* free (zero) the appropriate bits within this
2381 			 * dmap word.
2382 			 */
2383 			dp->wmap[word] &=
2384 			    cpu_to_le32(~(ONES << (DBWORD - nb)
2385 					  >> wbitno));
2386 
2387 			/* update the leaf for this dmap word.
2388 			 */
2389 			rc = dbJoin(tp, word,
2390 				    dbMaxBud((u8 *) & dp->wmap[word]));
2391 			if (rc)
2392 				return rc;
2393 
2394 			word += 1;
2395 		} else {
2396 			/* one or more dmap words are fully contained
2397 			 * within the block range.  determine how many
2398 			 * words and free (zero) the bits of these words.
2399 			 */
2400 			nwords = rembits >> L2DBWORD;
2401 			memset(&dp->wmap[word], 0, nwords * 4);
2402 
2403 			/* determine how many bits.
2404 			 */
2405 			nb = nwords << L2DBWORD;
2406 
2407 			/* now update the appropriate leaves to reflect
2408 			 * the freed words.
2409 			 */
2410 			for (; nwords > 0; nwords -= nw) {
2411 				/* determine what the leaf value should be
2412 				 * updated to as the minimum of the l2 number
2413 				 * of bits being freed and the l2 (max) number
2414 				 * of bits that can be described by this leaf.
2415 				 */
2416 				size =
2417 				    min(LITOL2BSZ
2418 					(word, L2LPERDMAP, BUDMIN),
2419 					NLSTOL2BSZ(nwords));
2420 
2421 				/* update the leaf.
2422 				 */
2423 				rc = dbJoin(tp, word, size);
2424 				if (rc)
2425 					return rc;
2426 
2427 				/* get the number of dmap words handled.
2428 				 */
2429 				nw = BUDSIZE(size, BUDMIN);
2430 				word += nw;
2431 			}
2432 		}
2433 	}
2434 
2435 	/* update the free count for this dmap.
2436 	 */
2437 	le32_add_cpu(&dp->nfree, nblocks);
2438 
2439 	BMAP_LOCK(bmp);
2440 
2441 	/* update the free count for the allocation group and
2442 	 * map.
2443 	 */
2444 	agno = blkno >> bmp->db_agl2size;
2445 	bmp->db_nfree += nblocks;
2446 	bmp->db_agfree[agno] += nblocks;
2447 
2448 	/* check if this allocation group is not completely free and
2449 	 * if it is currently the maximum (rightmost) allocation group.
2450 	 * if so, establish the new maximum allocation group number by
2451 	 * searching left for the first allocation group with allocation.
2452 	 */
2453 	if ((bmp->db_agfree[agno] == bmp->db_agsize && agno == bmp->db_maxag) ||
2454 	    (agno == bmp->db_numag - 1 &&
2455 	     bmp->db_agfree[agno] == (bmp-> db_mapsize & (BPERDMAP - 1)))) {
2456 		while (bmp->db_maxag > 0) {
2457 			bmp->db_maxag -= 1;
2458 			if (bmp->db_agfree[bmp->db_maxag] !=
2459 			    bmp->db_agsize)
2460 				break;
2461 		}
2462 
2463 		/* re-establish the allocation group preference if the
2464 		 * current preference is right of the maximum allocation
2465 		 * group.
2466 		 */
2467 		if (bmp->db_agpref > bmp->db_maxag)
2468 			bmp->db_agpref = bmp->db_maxag;
2469 	}
2470 
2471 	BMAP_UNLOCK(bmp);
2472 
2473 	return 0;
2474 }
2475 
2476 
2477 /*
2478  * NAME:	dbAdjCtl()
2479  *
2480  * FUNCTION:	adjust a dmap control page at a specified level to reflect
2481  *		the change in a lower level dmap or dmap control page's
2482  *		maximum string of free blocks (i.e. a change in the root
2483  *		of the lower level object's dmtree) due to the allocation
2484  *		or deallocation of a range of blocks with a single dmap.
2485  *
2486  *		on entry, this routine is provided with the new value of
2487  *		the lower level dmap or dmap control page root and the
2488  *		starting block number of the block range whose allocation
2489  *		or deallocation resulted in the root change.  this range
2490  *		is respresented by a single leaf of the current dmapctl
2491  *		and the leaf will be updated with this value, possibly
2492  *		causing a binary buddy system within the leaves to be
2493  *		split or joined.  the update may also cause the dmapctl's
2494  *		dmtree to be updated.
2495  *
2496  *		if the adjustment of the dmap control page, itself, causes its
2497  *		root to change, this change will be bubbled up to the next dmap
2498  *		control level by a recursive call to this routine, specifying
2499  *		the new root value and the next dmap control page level to
2500  *		be adjusted.
2501  * PARAMETERS:
2502  *	bmp	-  pointer to bmap descriptor
2503  *	blkno	-  the first block of a block range within a dmap.  it is
2504  *		   the allocation or deallocation of this block range that
2505  *		   requires the dmap control page to be adjusted.
2506  *	newval	-  the new value of the lower level dmap or dmap control
2507  *		   page root.
2508  *	alloc	-  'true' if adjustment is due to an allocation.
2509  *	level	-  current level of dmap control page (i.e. L0, L1, L2) to
2510  *		   be adjusted.
2511  *
2512  * RETURN VALUES:
2513  *	0	- success
2514  *	-EIO	- i/o error
2515  *
2516  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2517  */
2518 static int
dbAdjCtl(struct bmap * bmp,s64 blkno,int newval,int alloc,int level)2519 dbAdjCtl(struct bmap * bmp, s64 blkno, int newval, int alloc, int level)
2520 {
2521 	struct metapage *mp;
2522 	s8 oldroot;
2523 	int oldval;
2524 	s64 lblkno;
2525 	struct dmapctl *dcp;
2526 	int rc, leafno, ti;
2527 
2528 	/* get the buffer for the dmap control page for the specified
2529 	 * block number and control page level.
2530 	 */
2531 	lblkno = BLKTOCTL(blkno, bmp->db_l2nbperpage, level);
2532 	mp = read_metapage(bmp->db_ipbmap, lblkno, PSIZE, 0);
2533 	if (mp == NULL)
2534 		return -EIO;
2535 	dcp = (struct dmapctl *) mp->data;
2536 
2537 	if (dcp->leafidx != cpu_to_le32(CTLLEAFIND)) {
2538 		jfs_error(bmp->db_ipbmap->i_sb, "Corrupt dmapctl page\n");
2539 		release_metapage(mp);
2540 		return -EIO;
2541 	}
2542 
2543 	/* determine the leaf number corresponding to the block and
2544 	 * the index within the dmap control tree.
2545 	 */
2546 	leafno = BLKTOCTLLEAF(blkno, dcp->budmin);
2547 	ti = leafno + le32_to_cpu(dcp->leafidx);
2548 
2549 	/* save the current leaf value and the current root level (i.e.
2550 	 * maximum l2 free string described by this dmapctl).
2551 	 */
2552 	oldval = dcp->stree[ti];
2553 	oldroot = dcp->stree[ROOT];
2554 
2555 	/* check if this is a control page update for an allocation.
2556 	 * if so, update the leaf to reflect the new leaf value using
2557 	 * dbSplit(); otherwise (deallocation), use dbJoin() to update
2558 	 * the leaf with the new value.  in addition to updating the
2559 	 * leaf, dbSplit() will also split the binary buddy system of
2560 	 * the leaves, if required, and bubble new values within the
2561 	 * dmapctl tree, if required.  similarly, dbJoin() will join
2562 	 * the binary buddy system of leaves and bubble new values up
2563 	 * the dmapctl tree as required by the new leaf value.
2564 	 */
2565 	if (alloc) {
2566 		/* check if we are in the middle of a binary buddy
2567 		 * system.  this happens when we are performing the
2568 		 * first allocation out of an allocation group that
2569 		 * is part (not the first part) of a larger binary
2570 		 * buddy system.  if we are in the middle, back split
2571 		 * the system prior to calling dbSplit() which assumes
2572 		 * that it is at the front of a binary buddy system.
2573 		 */
2574 		if (oldval == NOFREE) {
2575 			rc = dbBackSplit((dmtree_t *) dcp, leafno);
2576 			if (rc)
2577 				return rc;
2578 			oldval = dcp->stree[ti];
2579 		}
2580 		dbSplit((dmtree_t *) dcp, leafno, dcp->budmin, newval);
2581 	} else {
2582 		rc = dbJoin((dmtree_t *) dcp, leafno, newval);
2583 		if (rc)
2584 			return rc;
2585 	}
2586 
2587 	/* check if the root of the current dmap control page changed due
2588 	 * to the update and if the current dmap control page is not at
2589 	 * the current top level (i.e. L0, L1, L2) of the map.  if so (i.e.
2590 	 * root changed and this is not the top level), call this routine
2591 	 * again (recursion) for the next higher level of the mapping to
2592 	 * reflect the change in root for the current dmap control page.
2593 	 */
2594 	if (dcp->stree[ROOT] != oldroot) {
2595 		/* are we below the top level of the map.  if so,
2596 		 * bubble the root up to the next higher level.
2597 		 */
2598 		if (level < bmp->db_maxlevel) {
2599 			/* bubble up the new root of this dmap control page to
2600 			 * the next level.
2601 			 */
2602 			if ((rc =
2603 			     dbAdjCtl(bmp, blkno, dcp->stree[ROOT], alloc,
2604 				      level + 1))) {
2605 				/* something went wrong in bubbling up the new
2606 				 * root value, so backout the changes to the
2607 				 * current dmap control page.
2608 				 */
2609 				if (alloc) {
2610 					dbJoin((dmtree_t *) dcp, leafno,
2611 					       oldval);
2612 				} else {
2613 					/* the dbJoin() above might have
2614 					 * caused a larger binary buddy system
2615 					 * to form and we may now be in the
2616 					 * middle of it.  if this is the case,
2617 					 * back split the buddies.
2618 					 */
2619 					if (dcp->stree[ti] == NOFREE)
2620 						dbBackSplit((dmtree_t *)
2621 							    dcp, leafno);
2622 					dbSplit((dmtree_t *) dcp, leafno,
2623 						dcp->budmin, oldval);
2624 				}
2625 
2626 				/* release the buffer and return the error.
2627 				 */
2628 				release_metapage(mp);
2629 				return (rc);
2630 			}
2631 		} else {
2632 			/* we're at the top level of the map. update
2633 			 * the bmap control page to reflect the size
2634 			 * of the maximum free buddy system.
2635 			 */
2636 			assert(level == bmp->db_maxlevel);
2637 			if (bmp->db_maxfreebud != oldroot) {
2638 				jfs_error(bmp->db_ipbmap->i_sb,
2639 					  "the maximum free buddy is not the old root\n");
2640 			}
2641 			bmp->db_maxfreebud = dcp->stree[ROOT];
2642 		}
2643 	}
2644 
2645 	/* write the buffer.
2646 	 */
2647 	write_metapage(mp);
2648 
2649 	return (0);
2650 }
2651 
2652 
2653 /*
2654  * NAME:	dbSplit()
2655  *
2656  * FUNCTION:	update the leaf of a dmtree with a new value, splitting
2657  *		the leaf from the binary buddy system of the dmtree's
2658  *		leaves, as required.
2659  *
2660  * PARAMETERS:
2661  *	tp	- pointer to the tree containing the leaf.
2662  *	leafno	- the number of the leaf to be updated.
2663  *	splitsz	- the size the binary buddy system starting at the leaf
2664  *		  must be split to, specified as the log2 number of blocks.
2665  *	newval	- the new value for the leaf.
2666  *
2667  * RETURN VALUES: none
2668  *
2669  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2670  */
dbSplit(dmtree_t * tp,int leafno,int splitsz,int newval)2671 static void dbSplit(dmtree_t * tp, int leafno, int splitsz, int newval)
2672 {
2673 	int budsz;
2674 	int cursz;
2675 	s8 *leaf = tp->dmt_stree + le32_to_cpu(tp->dmt_leafidx);
2676 
2677 	/* check if the leaf needs to be split.
2678 	 */
2679 	if (leaf[leafno] > tp->dmt_budmin) {
2680 		/* the split occurs by cutting the buddy system in half
2681 		 * at the specified leaf until we reach the specified
2682 		 * size.  pick up the starting split size (current size
2683 		 * - 1 in l2) and the corresponding buddy size.
2684 		 */
2685 		cursz = leaf[leafno] - 1;
2686 		budsz = BUDSIZE(cursz, tp->dmt_budmin);
2687 
2688 		/* split until we reach the specified size.
2689 		 */
2690 		while (cursz >= splitsz) {
2691 			/* update the buddy's leaf with its new value.
2692 			 */
2693 			dbAdjTree(tp, leafno ^ budsz, cursz);
2694 
2695 			/* on to the next size and buddy.
2696 			 */
2697 			cursz -= 1;
2698 			budsz >>= 1;
2699 		}
2700 	}
2701 
2702 	/* adjust the dmap tree to reflect the specified leaf's new
2703 	 * value.
2704 	 */
2705 	dbAdjTree(tp, leafno, newval);
2706 }
2707 
2708 
2709 /*
2710  * NAME:	dbBackSplit()
2711  *
2712  * FUNCTION:	back split the binary buddy system of dmtree leaves
2713  *		that hold a specified leaf until the specified leaf
2714  *		starts its own binary buddy system.
2715  *
2716  *		the allocators typically perform allocations at the start
2717  *		of binary buddy systems and dbSplit() is used to accomplish
2718  *		any required splits.  in some cases, however, allocation
2719  *		may occur in the middle of a binary system and requires a
2720  *		back split, with the split proceeding out from the middle of
2721  *		the system (less efficient) rather than the start of the
2722  *		system (more efficient).  the cases in which a back split
2723  *		is required are rare and are limited to the first allocation
2724  *		within an allocation group which is a part (not first part)
2725  *		of a larger binary buddy system and a few exception cases
2726  *		in which a previous join operation must be backed out.
2727  *
2728  * PARAMETERS:
2729  *	tp	- pointer to the tree containing the leaf.
2730  *	leafno	- the number of the leaf to be updated.
2731  *
2732  * RETURN VALUES: none
2733  *
2734  * serialization: IREAD_LOCK(ipbmap) or IWRITE_LOCK(ipbmap) held on entry/exit;
2735  */
dbBackSplit(dmtree_t * tp,int leafno)2736 static int dbBackSplit(dmtree_t * tp, int leafno)
2737 {
2738 	int budsz, bud, w, bsz, size;
2739 	int cursz;
2740 	s8 *leaf = tp->dmt_stree + le32_to_cpu(tp->dmt_leafidx);
2741 
2742 	/* leaf should be part (not first part) of a binary
2743 	 * buddy system.
2744 	 */
2745 	assert(leaf[leafno] == NOFREE);
2746 
2747 	/* the back split is accomplished by iteratively finding the leaf
2748 	 * that starts the buddy system that contains the specified leaf and
2749 	 * splitting that system in two.  this iteration continues until
2750 	 * the specified leaf becomes the start of a buddy system.
2751 	 *
2752 	 * determine maximum possible l2 size for the specified leaf.
2753 	 */
2754 	size =
2755 	    LITOL2BSZ(leafno, le32_to_cpu(tp->dmt_l2nleafs),
2756 		      tp->dmt_budmin);
2757 
2758 	/* determine the number of leaves covered by this size.  this
2759 	 * is the buddy size that we will start with as we search for
2760 	 * the buddy system that contains the specified leaf.
2761 	 */
2762 	budsz = BUDSIZE(size, tp->dmt_budmin);
2763 
2764 	/* back split.
2765 	 */
2766 	while (leaf[leafno] == NOFREE) {
2767 		/* find the leftmost buddy leaf.
2768 		 */
2769 		for (w = leafno, bsz = budsz;; bsz <<= 1,
2770 		     w = (w < bud) ? w : bud) {
2771 			if (bsz >= le32_to_cpu(tp->dmt_nleafs)) {
2772 				jfs_err("JFS: block map error in dbBackSplit");
2773 				return -EIO;
2774 			}
2775 
2776 			/* determine the buddy.
2777 			 */
2778 			bud = w ^ bsz;
2779 
2780 			/* check if this buddy is the start of the system.
2781 			 */
2782 			if (leaf[bud] != NOFREE) {
2783 				/* split the leaf at the start of the
2784 				 * system in two.
2785 				 */
2786 				cursz = leaf[bud] - 1;
2787 				dbSplit(tp, bud, cursz, cursz);
2788 				break;
2789 			}
2790 		}
2791 	}
2792 
2793 	if (leaf[leafno] != size) {
2794 		jfs_err("JFS: wrong leaf value in dbBackSplit");
2795 		return -EIO;
2796 	}
2797 	return 0;
2798 }
2799 
2800 
2801 /*
2802  * NAME:	dbJoin()
2803  *
2804  * FUNCTION:	update the leaf of a dmtree with a new value, joining
2805  *		the leaf with other leaves of the dmtree into a multi-leaf
2806  *		binary buddy system, as required.
2807  *
2808  * PARAMETERS:
2809  *	tp	- pointer to the tree containing the leaf.
2810  *	leafno	- the number of the leaf to be updated.
2811  *	newval	- the new value for the leaf.
2812  *
2813  * RETURN VALUES: none
2814  */
dbJoin(dmtree_t * tp,int leafno,int newval)2815 static int dbJoin(dmtree_t * tp, int leafno, int newval)
2816 {
2817 	int budsz, buddy;
2818 	s8 *leaf;
2819 
2820 	/* can the new leaf value require a join with other leaves ?
2821 	 */
2822 	if (newval >= tp->dmt_budmin) {
2823 		/* pickup a pointer to the leaves of the tree.
2824 		 */
2825 		leaf = tp->dmt_stree + le32_to_cpu(tp->dmt_leafidx);
2826 
2827 		/* try to join the specified leaf into a large binary
2828 		 * buddy system.  the join proceeds by attempting to join
2829 		 * the specified leafno with its buddy (leaf) at new value.
2830 		 * if the join occurs, we attempt to join the left leaf
2831 		 * of the joined buddies with its buddy at new value + 1.
2832 		 * we continue to join until we find a buddy that cannot be
2833 		 * joined (does not have a value equal to the size of the
2834 		 * last join) or until all leaves have been joined into a
2835 		 * single system.
2836 		 *
2837 		 * get the buddy size (number of words covered) of
2838 		 * the new value.
2839 		 */
2840 		budsz = BUDSIZE(newval, tp->dmt_budmin);
2841 
2842 		/* try to join.
2843 		 */
2844 		while (budsz < le32_to_cpu(tp->dmt_nleafs)) {
2845 			/* get the buddy leaf.
2846 			 */
2847 			buddy = leafno ^ budsz;
2848 
2849 			/* if the leaf's new value is greater than its
2850 			 * buddy's value, we join no more.
2851 			 */
2852 			if (newval > leaf[buddy])
2853 				break;
2854 
2855 			/* It shouldn't be less */
2856 			if (newval < leaf[buddy])
2857 				return -EIO;
2858 
2859 			/* check which (leafno or buddy) is the left buddy.
2860 			 * the left buddy gets to claim the blocks resulting
2861 			 * from the join while the right gets to claim none.
2862 			 * the left buddy is also eligible to participate in
2863 			 * a join at the next higher level while the right
2864 			 * is not.
2865 			 *
2866 			 */
2867 			if (leafno < buddy) {
2868 				/* leafno is the left buddy.
2869 				 */
2870 				dbAdjTree(tp, buddy, NOFREE);
2871 			} else {
2872 				/* buddy is the left buddy and becomes
2873 				 * leafno.
2874 				 */
2875 				dbAdjTree(tp, leafno, NOFREE);
2876 				leafno = buddy;
2877 			}
2878 
2879 			/* on to try the next join.
2880 			 */
2881 			newval += 1;
2882 			budsz <<= 1;
2883 		}
2884 	}
2885 
2886 	/* update the leaf value.
2887 	 */
2888 	dbAdjTree(tp, leafno, newval);
2889 
2890 	return 0;
2891 }
2892 
2893 
2894 /*
2895  * NAME:	dbAdjTree()
2896  *
2897  * FUNCTION:	update a leaf of a dmtree with a new value, adjusting
2898  *		the dmtree, as required, to reflect the new leaf value.
2899  *		the combination of any buddies must already be done before
2900  *		this is called.
2901  *
2902  * PARAMETERS:
2903  *	tp	- pointer to the tree to be adjusted.
2904  *	leafno	- the number of the leaf to be updated.
2905  *	newval	- the new value for the leaf.
2906  *
2907  * RETURN VALUES: none
2908  */
dbAdjTree(dmtree_t * tp,int leafno,int newval)2909 static void dbAdjTree(dmtree_t * tp, int leafno, int newval)
2910 {
2911 	int lp, pp, k;
2912 	int max;
2913 
2914 	/* pick up the index of the leaf for this leafno.
2915 	 */
2916 	lp = leafno + le32_to_cpu(tp->dmt_leafidx);
2917 
2918 	/* is the current value the same as the old value ?  if so,
2919 	 * there is nothing to do.
2920 	 */
2921 	if (tp->dmt_stree[lp] == newval)
2922 		return;
2923 
2924 	/* set the new value.
2925 	 */
2926 	tp->dmt_stree[lp] = newval;
2927 
2928 	/* bubble the new value up the tree as required.
2929 	 */
2930 	for (k = 0; k < le32_to_cpu(tp->dmt_height); k++) {
2931 		/* get the index of the first leaf of the 4 leaf
2932 		 * group containing the specified leaf (leafno).
2933 		 */
2934 		lp = ((lp - 1) & ~0x03) + 1;
2935 
2936 		/* get the index of the parent of this 4 leaf group.
2937 		 */
2938 		pp = (lp - 1) >> 2;
2939 
2940 		/* determine the maximum of the 4 leaves.
2941 		 */
2942 		max = TREEMAX(&tp->dmt_stree[lp]);
2943 
2944 		/* if the maximum of the 4 is the same as the
2945 		 * parent's value, we're done.
2946 		 */
2947 		if (tp->dmt_stree[pp] == max)
2948 			break;
2949 
2950 		/* parent gets new value.
2951 		 */
2952 		tp->dmt_stree[pp] = max;
2953 
2954 		/* parent becomes leaf for next go-round.
2955 		 */
2956 		lp = pp;
2957 	}
2958 }
2959 
2960 
2961 /*
2962  * NAME:	dbFindLeaf()
2963  *
2964  * FUNCTION:	search a dmtree_t for sufficient free blocks, returning
2965  *		the index of a leaf describing the free blocks if
2966  *		sufficient free blocks are found.
2967  *
2968  *		the search starts at the top of the dmtree_t tree and
2969  *		proceeds down the tree to the leftmost leaf with sufficient
2970  *		free space.
2971  *
2972  * PARAMETERS:
2973  *	tp	- pointer to the tree to be searched.
2974  *	l2nb	- log2 number of free blocks to search for.
2975  *	leafidx	- return pointer to be set to the index of the leaf
2976  *		  describing at least l2nb free blocks if sufficient
2977  *		  free blocks are found.
2978  *
2979  * RETURN VALUES:
2980  *	0	- success
2981  *	-ENOSPC	- insufficient free blocks.
2982  */
dbFindLeaf(dmtree_t * tp,int l2nb,int * leafidx)2983 static int dbFindLeaf(dmtree_t * tp, int l2nb, int *leafidx)
2984 {
2985 	int ti, n = 0, k, x = 0;
2986 
2987 	/* first check the root of the tree to see if there is
2988 	 * sufficient free space.
2989 	 */
2990 	if (l2nb > tp->dmt_stree[ROOT])
2991 		return -ENOSPC;
2992 
2993 	/* sufficient free space available. now search down the tree
2994 	 * starting at the next level for the leftmost leaf that
2995 	 * describes sufficient free space.
2996 	 */
2997 	for (k = le32_to_cpu(tp->dmt_height), ti = 1;
2998 	     k > 0; k--, ti = ((ti + n) << 2) + 1) {
2999 		/* search the four nodes at this level, starting from
3000 		 * the left.
3001 		 */
3002 		for (x = ti, n = 0; n < 4; n++) {
3003 			/* sufficient free space found.  move to the next
3004 			 * level (or quit if this is the last level).
3005 			 */
3006 			if (l2nb <= tp->dmt_stree[x + n])
3007 				break;
3008 		}
3009 
3010 		/* better have found something since the higher
3011 		 * levels of the tree said it was here.
3012 		 */
3013 		assert(n < 4);
3014 	}
3015 
3016 	/* set the return to the leftmost leaf describing sufficient
3017 	 * free space.
3018 	 */
3019 	*leafidx = x + n - le32_to_cpu(tp->dmt_leafidx);
3020 
3021 	return (0);
3022 }
3023 
3024 
3025 /*
3026  * NAME:	dbFindBits()
3027  *
3028  * FUNCTION:	find a specified number of binary buddy free bits within a
3029  *		dmap bitmap word value.
3030  *
3031  *		this routine searches the bitmap value for (1 << l2nb) free
3032  *		bits at (1 << l2nb) alignments within the value.
3033  *
3034  * PARAMETERS:
3035  *	word	-  dmap bitmap word value.
3036  *	l2nb	-  number of free bits specified as a log2 number.
3037  *
3038  * RETURN VALUES:
3039  *	starting bit number of free bits.
3040  */
dbFindBits(u32 word,int l2nb)3041 static int dbFindBits(u32 word, int l2nb)
3042 {
3043 	int bitno, nb;
3044 	u32 mask;
3045 
3046 	/* get the number of bits.
3047 	 */
3048 	nb = 1 << l2nb;
3049 	assert(nb <= DBWORD);
3050 
3051 	/* complement the word so we can use a mask (i.e. 0s represent
3052 	 * free bits) and compute the mask.
3053 	 */
3054 	word = ~word;
3055 	mask = ONES << (DBWORD - nb);
3056 
3057 	/* scan the word for nb free bits at nb alignments.
3058 	 */
3059 	for (bitno = 0; mask != 0; bitno += nb, mask >>= nb) {
3060 		if ((mask & word) == mask)
3061 			break;
3062 	}
3063 
3064 	ASSERT(bitno < 32);
3065 
3066 	/* return the bit number.
3067 	 */
3068 	return (bitno);
3069 }
3070 
3071 
3072 /*
3073  * NAME:	dbMaxBud(u8 *cp)
3074  *
3075  * FUNCTION:	determine the largest binary buddy string of free
3076  *		bits within 32-bits of the map.
3077  *
3078  * PARAMETERS:
3079  *	cp	-  pointer to the 32-bit value.
3080  *
3081  * RETURN VALUES:
3082  *	largest binary buddy of free bits within a dmap word.
3083  */
dbMaxBud(u8 * cp)3084 static int dbMaxBud(u8 * cp)
3085 {
3086 	signed char tmp1, tmp2;
3087 
3088 	/* check if the wmap word is all free. if so, the
3089 	 * free buddy size is BUDMIN.
3090 	 */
3091 	if (*((uint *) cp) == 0)
3092 		return (BUDMIN);
3093 
3094 	/* check if the wmap word is half free. if so, the
3095 	 * free buddy size is BUDMIN-1.
3096 	 */
3097 	if (*((u16 *) cp) == 0 || *((u16 *) cp + 1) == 0)
3098 		return (BUDMIN - 1);
3099 
3100 	/* not all free or half free. determine the free buddy
3101 	 * size thru table lookup using quarters of the wmap word.
3102 	 */
3103 	tmp1 = max(budtab[cp[2]], budtab[cp[3]]);
3104 	tmp2 = max(budtab[cp[0]], budtab[cp[1]]);
3105 	return (max(tmp1, tmp2));
3106 }
3107 
3108 
3109 /*
3110  * NAME:	cnttz(uint word)
3111  *
3112  * FUNCTION:	determine the number of trailing zeros within a 32-bit
3113  *		value.
3114  *
3115  * PARAMETERS:
3116  *	value	-  32-bit value to be examined.
3117  *
3118  * RETURN VALUES:
3119  *	count of trailing zeros
3120  */
cnttz(u32 word)3121 static int cnttz(u32 word)
3122 {
3123 	int n;
3124 
3125 	for (n = 0; n < 32; n++, word >>= 1) {
3126 		if (word & 0x01)
3127 			break;
3128 	}
3129 
3130 	return (n);
3131 }
3132 
3133 
3134 /*
3135  * NAME:	cntlz(u32 value)
3136  *
3137  * FUNCTION:	determine the number of leading zeros within a 32-bit
3138  *		value.
3139  *
3140  * PARAMETERS:
3141  *	value	-  32-bit value to be examined.
3142  *
3143  * RETURN VALUES:
3144  *	count of leading zeros
3145  */
cntlz(u32 value)3146 static int cntlz(u32 value)
3147 {
3148 	int n;
3149 
3150 	for (n = 0; n < 32; n++, value <<= 1) {
3151 		if (value & HIGHORDER)
3152 			break;
3153 	}
3154 	return (n);
3155 }
3156 
3157 
3158 /*
3159  * NAME:	blkstol2(s64 nb)
3160  *
3161  * FUNCTION:	convert a block count to its log2 value. if the block
3162  *		count is not a l2 multiple, it is rounded up to the next
3163  *		larger l2 multiple.
3164  *
3165  * PARAMETERS:
3166  *	nb	-  number of blocks
3167  *
3168  * RETURN VALUES:
3169  *	log2 number of blocks
3170  */
blkstol2(s64 nb)3171 static int blkstol2(s64 nb)
3172 {
3173 	int l2nb;
3174 	s64 mask;		/* meant to be signed */
3175 
3176 	mask = (s64) 1 << (64 - 1);
3177 
3178 	/* count the leading bits.
3179 	 */
3180 	for (l2nb = 0; l2nb < 64; l2nb++, mask >>= 1) {
3181 		/* leading bit found.
3182 		 */
3183 		if (nb & mask) {
3184 			/* determine the l2 value.
3185 			 */
3186 			l2nb = (64 - 1) - l2nb;
3187 
3188 			/* check if we need to round up.
3189 			 */
3190 			if (~mask & nb)
3191 				l2nb++;
3192 
3193 			return (l2nb);
3194 		}
3195 	}
3196 	assert(0);
3197 	return 0;		/* fix compiler warning */
3198 }
3199 
3200 
3201 /*
3202  * NAME:	dbAllocBottomUp()
3203  *
3204  * FUNCTION:	alloc the specified block range from the working block
3205  *		allocation map.
3206  *
3207  *		the blocks will be alloc from the working map one dmap
3208  *		at a time.
3209  *
3210  * PARAMETERS:
3211  *	ip	-  pointer to in-core inode;
3212  *	blkno	-  starting block number to be freed.
3213  *	nblocks	-  number of blocks to be freed.
3214  *
3215  * RETURN VALUES:
3216  *	0	- success
3217  *	-EIO	- i/o error
3218  */
dbAllocBottomUp(struct inode * ip,s64 blkno,s64 nblocks)3219 int dbAllocBottomUp(struct inode *ip, s64 blkno, s64 nblocks)
3220 {
3221 	struct metapage *mp;
3222 	struct dmap *dp;
3223 	int nb, rc;
3224 	s64 lblkno, rem;
3225 	struct inode *ipbmap = JFS_SBI(ip->i_sb)->ipbmap;
3226 	struct bmap *bmp = JFS_SBI(ip->i_sb)->bmap;
3227 
3228 	IREAD_LOCK(ipbmap, RDWRLOCK_DMAP);
3229 
3230 	/* block to be allocated better be within the mapsize. */
3231 	ASSERT(nblocks <= bmp->db_mapsize - blkno);
3232 
3233 	/*
3234 	 * allocate the blocks a dmap at a time.
3235 	 */
3236 	mp = NULL;
3237 	for (rem = nblocks; rem > 0; rem -= nb, blkno += nb) {
3238 		/* release previous dmap if any */
3239 		if (mp) {
3240 			write_metapage(mp);
3241 		}
3242 
3243 		/* get the buffer for the current dmap. */
3244 		lblkno = BLKTODMAP(blkno, bmp->db_l2nbperpage);
3245 		mp = read_metapage(ipbmap, lblkno, PSIZE, 0);
3246 		if (mp == NULL) {
3247 			IREAD_UNLOCK(ipbmap);
3248 			return -EIO;
3249 		}
3250 		dp = (struct dmap *) mp->data;
3251 
3252 		/* determine the number of blocks to be allocated from
3253 		 * this dmap.
3254 		 */
3255 		nb = min(rem, BPERDMAP - (blkno & (BPERDMAP - 1)));
3256 
3257 		/* allocate the blocks. */
3258 		if ((rc = dbAllocDmapBU(bmp, dp, blkno, nb))) {
3259 			release_metapage(mp);
3260 			IREAD_UNLOCK(ipbmap);
3261 			return (rc);
3262 		}
3263 	}
3264 
3265 	/* write the last buffer. */
3266 	write_metapage(mp);
3267 
3268 	IREAD_UNLOCK(ipbmap);
3269 
3270 	return (0);
3271 }
3272 
3273 
dbAllocDmapBU(struct bmap * bmp,struct dmap * dp,s64 blkno,int nblocks)3274 static int dbAllocDmapBU(struct bmap * bmp, struct dmap * dp, s64 blkno,
3275 			 int nblocks)
3276 {
3277 	int rc;
3278 	int dbitno, word, rembits, nb, nwords, wbitno, agno;
3279 	s8 oldroot;
3280 	struct dmaptree *tp = (struct dmaptree *) & dp->tree;
3281 
3282 	/* save the current value of the root (i.e. maximum free string)
3283 	 * of the dmap tree.
3284 	 */
3285 	oldroot = tp->stree[ROOT];
3286 
3287 	/* determine the bit number and word within the dmap of the
3288 	 * starting block.
3289 	 */
3290 	dbitno = blkno & (BPERDMAP - 1);
3291 	word = dbitno >> L2DBWORD;
3292 
3293 	/* block range better be within the dmap */
3294 	assert(dbitno + nblocks <= BPERDMAP);
3295 
3296 	/* allocate the bits of the dmap's words corresponding to the block
3297 	 * range. not all bits of the first and last words may be contained
3298 	 * within the block range.  if this is the case, we'll work against
3299 	 * those words (i.e. partial first and/or last) on an individual basis
3300 	 * (a single pass), allocating the bits of interest by hand and
3301 	 * updating the leaf corresponding to the dmap word. a single pass
3302 	 * will be used for all dmap words fully contained within the
3303 	 * specified range.  within this pass, the bits of all fully contained
3304 	 * dmap words will be marked as free in a single shot and the leaves
3305 	 * will be updated. a single leaf may describe the free space of
3306 	 * multiple dmap words, so we may update only a subset of the actual
3307 	 * leaves corresponding to the dmap words of the block range.
3308 	 */
3309 	for (rembits = nblocks; rembits > 0; rembits -= nb, dbitno += nb) {
3310 		/* determine the bit number within the word and
3311 		 * the number of bits within the word.
3312 		 */
3313 		wbitno = dbitno & (DBWORD - 1);
3314 		nb = min(rembits, DBWORD - wbitno);
3315 
3316 		/* check if only part of a word is to be allocated.
3317 		 */
3318 		if (nb < DBWORD) {
3319 			/* allocate (set to 1) the appropriate bits within
3320 			 * this dmap word.
3321 			 */
3322 			dp->wmap[word] |= cpu_to_le32(ONES << (DBWORD - nb)
3323 						      >> wbitno);
3324 
3325 			word++;
3326 		} else {
3327 			/* one or more dmap words are fully contained
3328 			 * within the block range.  determine how many
3329 			 * words and allocate (set to 1) the bits of these
3330 			 * words.
3331 			 */
3332 			nwords = rembits >> L2DBWORD;
3333 			memset(&dp->wmap[word], (int) ONES, nwords * 4);
3334 
3335 			/* determine how many bits */
3336 			nb = nwords << L2DBWORD;
3337 			word += nwords;
3338 		}
3339 	}
3340 
3341 	/* update the free count for this dmap */
3342 	le32_add_cpu(&dp->nfree, -nblocks);
3343 
3344 	/* reconstruct summary tree */
3345 	dbInitDmapTree(dp);
3346 
3347 	BMAP_LOCK(bmp);
3348 
3349 	/* if this allocation group is completely free,
3350 	 * update the highest active allocation group number
3351 	 * if this allocation group is the new max.
3352 	 */
3353 	agno = blkno >> bmp->db_agl2size;
3354 	if (agno > bmp->db_maxag)
3355 		bmp->db_maxag = agno;
3356 
3357 	/* update the free count for the allocation group and map */
3358 	bmp->db_agfree[agno] -= nblocks;
3359 	bmp->db_nfree -= nblocks;
3360 
3361 	BMAP_UNLOCK(bmp);
3362 
3363 	/* if the root has not changed, done. */
3364 	if (tp->stree[ROOT] == oldroot)
3365 		return (0);
3366 
3367 	/* root changed. bubble the change up to the dmap control pages.
3368 	 * if the adjustment of the upper level control pages fails,
3369 	 * backout the bit allocation (thus making everything consistent).
3370 	 */
3371 	if ((rc = dbAdjCtl(bmp, blkno, tp->stree[ROOT], 1, 0)))
3372 		dbFreeBits(bmp, dp, blkno, nblocks);
3373 
3374 	return (rc);
3375 }
3376 
3377 
3378 /*
3379  * NAME:	dbExtendFS()
3380  *
3381  * FUNCTION:	extend bmap from blkno for nblocks;
3382  *		dbExtendFS() updates bmap ready for dbAllocBottomUp();
3383  *
3384  * L2
3385  *  |
3386  *   L1---------------------------------L1
3387  *    |					 |
3388  *     L0---------L0---------L0		  L0---------L0---------L0
3389  *      |	   |	      |		   |	      |		 |
3390  *	 d0,...,dn  d0,...,dn  d0,...,dn    d0,...,dn  d0,...,dn  d0,.,dm;
3391  * L2L1L0d0,...,dnL0d0,...,dnL0d0,...,dnL1L0d0,...,dnL0d0,...,dnL0d0,..dm
3392  *
3393  * <---old---><----------------------------extend----------------------->
3394  */
dbExtendFS(struct inode * ipbmap,s64 blkno,s64 nblocks)3395 int dbExtendFS(struct inode *ipbmap, s64 blkno,	s64 nblocks)
3396 {
3397 	struct jfs_sb_info *sbi = JFS_SBI(ipbmap->i_sb);
3398 	int nbperpage = sbi->nbperpage;
3399 	int i, i0 = true, j, j0 = true, k, n;
3400 	s64 newsize;
3401 	s64 p;
3402 	struct metapage *mp, *l2mp, *l1mp = NULL, *l0mp = NULL;
3403 	struct dmapctl *l2dcp, *l1dcp, *l0dcp;
3404 	struct dmap *dp;
3405 	s8 *l0leaf, *l1leaf, *l2leaf;
3406 	struct bmap *bmp = sbi->bmap;
3407 	int agno, l2agsize, oldl2agsize;
3408 	s64 ag_rem;
3409 
3410 	newsize = blkno + nblocks;
3411 
3412 	jfs_info("dbExtendFS: blkno:%Ld nblocks:%Ld newsize:%Ld",
3413 		 (long long) blkno, (long long) nblocks, (long long) newsize);
3414 
3415 	/*
3416 	 *	initialize bmap control page.
3417 	 *
3418 	 * all the data in bmap control page should exclude
3419 	 * the mkfs hidden dmap page.
3420 	 */
3421 
3422 	/* update mapsize */
3423 	bmp->db_mapsize = newsize;
3424 	bmp->db_maxlevel = BMAPSZTOLEV(bmp->db_mapsize);
3425 
3426 	/* compute new AG size */
3427 	l2agsize = dbGetL2AGSize(newsize);
3428 	oldl2agsize = bmp->db_agl2size;
3429 
3430 	bmp->db_agl2size = l2agsize;
3431 	bmp->db_agsize = 1 << l2agsize;
3432 
3433 	/* compute new number of AG */
3434 	agno = bmp->db_numag;
3435 	bmp->db_numag = newsize >> l2agsize;
3436 	bmp->db_numag += ((u32) newsize % (u32) bmp->db_agsize) ? 1 : 0;
3437 
3438 	/*
3439 	 *	reconfigure db_agfree[]
3440 	 * from old AG configuration to new AG configuration;
3441 	 *
3442 	 * coalesce contiguous k (newAGSize/oldAGSize) AGs;
3443 	 * i.e., (AGi, ..., AGj) where i = k*n and j = k*(n+1) - 1 to AGn;
3444 	 * note: new AG size = old AG size * (2**x).
3445 	 */
3446 	if (l2agsize == oldl2agsize)
3447 		goto extend;
3448 	k = 1 << (l2agsize - oldl2agsize);
3449 	ag_rem = bmp->db_agfree[0];	/* save agfree[0] */
3450 	for (i = 0, n = 0; i < agno; n++) {
3451 		bmp->db_agfree[n] = 0;	/* init collection point */
3452 
3453 		/* coalesce contiguous k AGs; */
3454 		for (j = 0; j < k && i < agno; j++, i++) {
3455 			/* merge AGi to AGn */
3456 			bmp->db_agfree[n] += bmp->db_agfree[i];
3457 		}
3458 	}
3459 	bmp->db_agfree[0] += ag_rem;	/* restore agfree[0] */
3460 
3461 	for (; n < MAXAG; n++)
3462 		bmp->db_agfree[n] = 0;
3463 
3464 	/*
3465 	 * update highest active ag number
3466 	 */
3467 
3468 	bmp->db_maxag = bmp->db_maxag / k;
3469 
3470 	/*
3471 	 *	extend bmap
3472 	 *
3473 	 * update bit maps and corresponding level control pages;
3474 	 * global control page db_nfree, db_agfree[agno], db_maxfreebud;
3475 	 */
3476       extend:
3477 	/* get L2 page */
3478 	p = BMAPBLKNO + nbperpage;	/* L2 page */
3479 	l2mp = read_metapage(ipbmap, p, PSIZE, 0);
3480 	if (!l2mp) {
3481 		jfs_error(ipbmap->i_sb, "L2 page could not be read\n");
3482 		return -EIO;
3483 	}
3484 	l2dcp = (struct dmapctl *) l2mp->data;
3485 
3486 	/* compute start L1 */
3487 	k = blkno >> L2MAXL1SIZE;
3488 	l2leaf = l2dcp->stree + CTLLEAFIND + k;
3489 	p = BLKTOL1(blkno, sbi->l2nbperpage);	/* L1 page */
3490 
3491 	/*
3492 	 * extend each L1 in L2
3493 	 */
3494 	for (; k < LPERCTL; k++, p += nbperpage) {
3495 		/* get L1 page */
3496 		if (j0) {
3497 			/* read in L1 page: (blkno & (MAXL1SIZE - 1)) */
3498 			l1mp = read_metapage(ipbmap, p, PSIZE, 0);
3499 			if (l1mp == NULL)
3500 				goto errout;
3501 			l1dcp = (struct dmapctl *) l1mp->data;
3502 
3503 			/* compute start L0 */
3504 			j = (blkno & (MAXL1SIZE - 1)) >> L2MAXL0SIZE;
3505 			l1leaf = l1dcp->stree + CTLLEAFIND + j;
3506 			p = BLKTOL0(blkno, sbi->l2nbperpage);
3507 			j0 = false;
3508 		} else {
3509 			/* assign/init L1 page */
3510 			l1mp = get_metapage(ipbmap, p, PSIZE, 0);
3511 			if (l1mp == NULL)
3512 				goto errout;
3513 
3514 			l1dcp = (struct dmapctl *) l1mp->data;
3515 
3516 			/* compute start L0 */
3517 			j = 0;
3518 			l1leaf = l1dcp->stree + CTLLEAFIND;
3519 			p += nbperpage;	/* 1st L0 of L1.k */
3520 		}
3521 
3522 		/*
3523 		 * extend each L0 in L1
3524 		 */
3525 		for (; j < LPERCTL; j++) {
3526 			/* get L0 page */
3527 			if (i0) {
3528 				/* read in L0 page: (blkno & (MAXL0SIZE - 1)) */
3529 
3530 				l0mp = read_metapage(ipbmap, p, PSIZE, 0);
3531 				if (l0mp == NULL)
3532 					goto errout;
3533 				l0dcp = (struct dmapctl *) l0mp->data;
3534 
3535 				/* compute start dmap */
3536 				i = (blkno & (MAXL0SIZE - 1)) >>
3537 				    L2BPERDMAP;
3538 				l0leaf = l0dcp->stree + CTLLEAFIND + i;
3539 				p = BLKTODMAP(blkno,
3540 					      sbi->l2nbperpage);
3541 				i0 = false;
3542 			} else {
3543 				/* assign/init L0 page */
3544 				l0mp = get_metapage(ipbmap, p, PSIZE, 0);
3545 				if (l0mp == NULL)
3546 					goto errout;
3547 
3548 				l0dcp = (struct dmapctl *) l0mp->data;
3549 
3550 				/* compute start dmap */
3551 				i = 0;
3552 				l0leaf = l0dcp->stree + CTLLEAFIND;
3553 				p += nbperpage;	/* 1st dmap of L0.j */
3554 			}
3555 
3556 			/*
3557 			 * extend each dmap in L0
3558 			 */
3559 			for (; i < LPERCTL; i++) {
3560 				/*
3561 				 * reconstruct the dmap page, and
3562 				 * initialize corresponding parent L0 leaf
3563 				 */
3564 				if ((n = blkno & (BPERDMAP - 1))) {
3565 					/* read in dmap page: */
3566 					mp = read_metapage(ipbmap, p,
3567 							   PSIZE, 0);
3568 					if (mp == NULL)
3569 						goto errout;
3570 					n = min(nblocks, (s64)BPERDMAP - n);
3571 				} else {
3572 					/* assign/init dmap page */
3573 					mp = read_metapage(ipbmap, p,
3574 							   PSIZE, 0);
3575 					if (mp == NULL)
3576 						goto errout;
3577 
3578 					n = min_t(s64, nblocks, BPERDMAP);
3579 				}
3580 
3581 				dp = (struct dmap *) mp->data;
3582 				*l0leaf = dbInitDmap(dp, blkno, n);
3583 
3584 				bmp->db_nfree += n;
3585 				agno = le64_to_cpu(dp->start) >> l2agsize;
3586 				bmp->db_agfree[agno] += n;
3587 
3588 				write_metapage(mp);
3589 
3590 				l0leaf++;
3591 				p += nbperpage;
3592 
3593 				blkno += n;
3594 				nblocks -= n;
3595 				if (nblocks == 0)
3596 					break;
3597 			}	/* for each dmap in a L0 */
3598 
3599 			/*
3600 			 * build current L0 page from its leaves, and
3601 			 * initialize corresponding parent L1 leaf
3602 			 */
3603 			*l1leaf = dbInitDmapCtl(l0dcp, 0, ++i);
3604 			write_metapage(l0mp);
3605 			l0mp = NULL;
3606 
3607 			if (nblocks)
3608 				l1leaf++;	/* continue for next L0 */
3609 			else {
3610 				/* more than 1 L0 ? */
3611 				if (j > 0)
3612 					break;	/* build L1 page */
3613 				else {
3614 					/* summarize in global bmap page */
3615 					bmp->db_maxfreebud = *l1leaf;
3616 					release_metapage(l1mp);
3617 					release_metapage(l2mp);
3618 					goto finalize;
3619 				}
3620 			}
3621 		}		/* for each L0 in a L1 */
3622 
3623 		/*
3624 		 * build current L1 page from its leaves, and
3625 		 * initialize corresponding parent L2 leaf
3626 		 */
3627 		*l2leaf = dbInitDmapCtl(l1dcp, 1, ++j);
3628 		write_metapage(l1mp);
3629 		l1mp = NULL;
3630 
3631 		if (nblocks)
3632 			l2leaf++;	/* continue for next L1 */
3633 		else {
3634 			/* more than 1 L1 ? */
3635 			if (k > 0)
3636 				break;	/* build L2 page */
3637 			else {
3638 				/* summarize in global bmap page */
3639 				bmp->db_maxfreebud = *l2leaf;
3640 				release_metapage(l2mp);
3641 				goto finalize;
3642 			}
3643 		}
3644 	}			/* for each L1 in a L2 */
3645 
3646 	jfs_error(ipbmap->i_sb, "function has not returned as expected\n");
3647 errout:
3648 	if (l0mp)
3649 		release_metapage(l0mp);
3650 	if (l1mp)
3651 		release_metapage(l1mp);
3652 	release_metapage(l2mp);
3653 	return -EIO;
3654 
3655 	/*
3656 	 *	finalize bmap control page
3657 	 */
3658 finalize:
3659 
3660 	return 0;
3661 }
3662 
3663 
3664 /*
3665  *	dbFinalizeBmap()
3666  */
dbFinalizeBmap(struct inode * ipbmap)3667 void dbFinalizeBmap(struct inode *ipbmap)
3668 {
3669 	struct bmap *bmp = JFS_SBI(ipbmap->i_sb)->bmap;
3670 	int actags, inactags, l2nl;
3671 	s64 ag_rem, actfree, inactfree, avgfree;
3672 	int i, n;
3673 
3674 	/*
3675 	 *	finalize bmap control page
3676 	 */
3677 //finalize:
3678 	/*
3679 	 * compute db_agpref: preferred ag to allocate from
3680 	 * (the leftmost ag with average free space in it);
3681 	 */
3682 //agpref:
3683 	/* get the number of active ags and inacitve ags */
3684 	actags = bmp->db_maxag + 1;
3685 	inactags = bmp->db_numag - actags;
3686 	ag_rem = bmp->db_mapsize & (bmp->db_agsize - 1);	/* ??? */
3687 
3688 	/* determine how many blocks are in the inactive allocation
3689 	 * groups. in doing this, we must account for the fact that
3690 	 * the rightmost group might be a partial group (i.e. file
3691 	 * system size is not a multiple of the group size).
3692 	 */
3693 	inactfree = (inactags && ag_rem) ?
3694 	    ((inactags - 1) << bmp->db_agl2size) + ag_rem
3695 	    : inactags << bmp->db_agl2size;
3696 
3697 	/* determine how many free blocks are in the active
3698 	 * allocation groups plus the average number of free blocks
3699 	 * within the active ags.
3700 	 */
3701 	actfree = bmp->db_nfree - inactfree;
3702 	avgfree = (u32) actfree / (u32) actags;
3703 
3704 	/* if the preferred allocation group has not average free space.
3705 	 * re-establish the preferred group as the leftmost
3706 	 * group with average free space.
3707 	 */
3708 	if (bmp->db_agfree[bmp->db_agpref] < avgfree) {
3709 		for (bmp->db_agpref = 0; bmp->db_agpref < actags;
3710 		     bmp->db_agpref++) {
3711 			if (bmp->db_agfree[bmp->db_agpref] >= avgfree)
3712 				break;
3713 		}
3714 		if (bmp->db_agpref >= bmp->db_numag) {
3715 			jfs_error(ipbmap->i_sb,
3716 				  "cannot find ag with average freespace\n");
3717 		}
3718 	}
3719 
3720 	/*
3721 	 * compute db_aglevel, db_agheight, db_width, db_agstart:
3722 	 * an ag is covered in aglevel dmapctl summary tree,
3723 	 * at agheight level height (from leaf) with agwidth number of nodes
3724 	 * each, which starts at agstart index node of the smmary tree node
3725 	 * array;
3726 	 */
3727 	bmp->db_aglevel = BMAPSZTOLEV(bmp->db_agsize);
3728 	l2nl =
3729 	    bmp->db_agl2size - (L2BPERDMAP + bmp->db_aglevel * L2LPERCTL);
3730 	bmp->db_agheight = l2nl >> 1;
3731 	bmp->db_agwidth = 1 << (l2nl - (bmp->db_agheight << 1));
3732 	for (i = 5 - bmp->db_agheight, bmp->db_agstart = 0, n = 1; i > 0;
3733 	     i--) {
3734 		bmp->db_agstart += n;
3735 		n <<= 2;
3736 	}
3737 
3738 }
3739 
3740 
3741 /*
3742  * NAME:	dbInitDmap()/ujfs_idmap_page()
3743  *
3744  * FUNCTION:	initialize working/persistent bitmap of the dmap page
3745  *		for the specified number of blocks:
3746  *
3747  *		at entry, the bitmaps had been initialized as free (ZEROS);
3748  *		The number of blocks will only account for the actually
3749  *		existing blocks. Blocks which don't actually exist in
3750  *		the aggregate will be marked as allocated (ONES);
3751  *
3752  * PARAMETERS:
3753  *	dp	- pointer to page of map
3754  *	nblocks	- number of blocks this page
3755  *
3756  * RETURNS: NONE
3757  */
dbInitDmap(struct dmap * dp,s64 Blkno,int nblocks)3758 static int dbInitDmap(struct dmap * dp, s64 Blkno, int nblocks)
3759 {
3760 	int blkno, w, b, r, nw, nb, i;
3761 
3762 	/* starting block number within the dmap */
3763 	blkno = Blkno & (BPERDMAP - 1);
3764 
3765 	if (blkno == 0) {
3766 		dp->nblocks = dp->nfree = cpu_to_le32(nblocks);
3767 		dp->start = cpu_to_le64(Blkno);
3768 
3769 		if (nblocks == BPERDMAP) {
3770 			memset(&dp->wmap[0], 0, LPERDMAP * 4);
3771 			memset(&dp->pmap[0], 0, LPERDMAP * 4);
3772 			goto initTree;
3773 		}
3774 	} else {
3775 		le32_add_cpu(&dp->nblocks, nblocks);
3776 		le32_add_cpu(&dp->nfree, nblocks);
3777 	}
3778 
3779 	/* word number containing start block number */
3780 	w = blkno >> L2DBWORD;
3781 
3782 	/*
3783 	 * free the bits corresponding to the block range (ZEROS):
3784 	 * note: not all bits of the first and last words may be contained
3785 	 * within the block range.
3786 	 */
3787 	for (r = nblocks; r > 0; r -= nb, blkno += nb) {
3788 		/* number of bits preceding range to be freed in the word */
3789 		b = blkno & (DBWORD - 1);
3790 		/* number of bits to free in the word */
3791 		nb = min(r, DBWORD - b);
3792 
3793 		/* is partial word to be freed ? */
3794 		if (nb < DBWORD) {
3795 			/* free (set to 0) from the bitmap word */
3796 			dp->wmap[w] &= cpu_to_le32(~(ONES << (DBWORD - nb)
3797 						     >> b));
3798 			dp->pmap[w] &= cpu_to_le32(~(ONES << (DBWORD - nb)
3799 						     >> b));
3800 
3801 			/* skip the word freed */
3802 			w++;
3803 		} else {
3804 			/* free (set to 0) contiguous bitmap words */
3805 			nw = r >> L2DBWORD;
3806 			memset(&dp->wmap[w], 0, nw * 4);
3807 			memset(&dp->pmap[w], 0, nw * 4);
3808 
3809 			/* skip the words freed */
3810 			nb = nw << L2DBWORD;
3811 			w += nw;
3812 		}
3813 	}
3814 
3815 	/*
3816 	 * mark bits following the range to be freed (non-existing
3817 	 * blocks) as allocated (ONES)
3818 	 */
3819 
3820 	if (blkno == BPERDMAP)
3821 		goto initTree;
3822 
3823 	/* the first word beyond the end of existing blocks */
3824 	w = blkno >> L2DBWORD;
3825 
3826 	/* does nblocks fall on a 32-bit boundary ? */
3827 	b = blkno & (DBWORD - 1);
3828 	if (b) {
3829 		/* mark a partial word allocated */
3830 		dp->wmap[w] = dp->pmap[w] = cpu_to_le32(ONES >> b);
3831 		w++;
3832 	}
3833 
3834 	/* set the rest of the words in the page to allocated (ONES) */
3835 	for (i = w; i < LPERDMAP; i++)
3836 		dp->pmap[i] = dp->wmap[i] = cpu_to_le32(ONES);
3837 
3838 	/*
3839 	 * init tree
3840 	 */
3841       initTree:
3842 	return (dbInitDmapTree(dp));
3843 }
3844 
3845 
3846 /*
3847  * NAME:	dbInitDmapTree()/ujfs_complete_dmap()
3848  *
3849  * FUNCTION:	initialize summary tree of the specified dmap:
3850  *
3851  *		at entry, bitmap of the dmap has been initialized;
3852  *
3853  * PARAMETERS:
3854  *	dp	- dmap to complete
3855  *	blkno	- starting block number for this dmap
3856  *	treemax	- will be filled in with max free for this dmap
3857  *
3858  * RETURNS:	max free string at the root of the tree
3859  */
dbInitDmapTree(struct dmap * dp)3860 static int dbInitDmapTree(struct dmap * dp)
3861 {
3862 	struct dmaptree *tp;
3863 	s8 *cp;
3864 	int i;
3865 
3866 	/* init fixed info of tree */
3867 	tp = &dp->tree;
3868 	tp->nleafs = cpu_to_le32(LPERDMAP);
3869 	tp->l2nleafs = cpu_to_le32(L2LPERDMAP);
3870 	tp->leafidx = cpu_to_le32(LEAFIND);
3871 	tp->height = cpu_to_le32(4);
3872 	tp->budmin = BUDMIN;
3873 
3874 	/* init each leaf from corresponding wmap word:
3875 	 * note: leaf is set to NOFREE(-1) if all blocks of corresponding
3876 	 * bitmap word are allocated.
3877 	 */
3878 	cp = tp->stree + le32_to_cpu(tp->leafidx);
3879 	for (i = 0; i < LPERDMAP; i++)
3880 		*cp++ = dbMaxBud((u8 *) & dp->wmap[i]);
3881 
3882 	/* build the dmap's binary buddy summary tree */
3883 	return (dbInitTree(tp));
3884 }
3885 
3886 
3887 /*
3888  * NAME:	dbInitTree()/ujfs_adjtree()
3889  *
3890  * FUNCTION:	initialize binary buddy summary tree of a dmap or dmapctl.
3891  *
3892  *		at entry, the leaves of the tree has been initialized
3893  *		from corresponding bitmap word or root of summary tree
3894  *		of the child control page;
3895  *		configure binary buddy system at the leaf level, then
3896  *		bubble up the values of the leaf nodes up the tree.
3897  *
3898  * PARAMETERS:
3899  *	cp	- Pointer to the root of the tree
3900  *	l2leaves- Number of leaf nodes as a power of 2
3901  *	l2min	- Number of blocks that can be covered by a leaf
3902  *		  as a power of 2
3903  *
3904  * RETURNS: max free string at the root of the tree
3905  */
dbInitTree(struct dmaptree * dtp)3906 static int dbInitTree(struct dmaptree * dtp)
3907 {
3908 	int l2max, l2free, bsize, nextb, i;
3909 	int child, parent, nparent;
3910 	s8 *tp, *cp, *cp1;
3911 
3912 	tp = dtp->stree;
3913 
3914 	/* Determine the maximum free string possible for the leaves */
3915 	l2max = le32_to_cpu(dtp->l2nleafs) + dtp->budmin;
3916 
3917 	/*
3918 	 * configure the leaf levevl into binary buddy system
3919 	 *
3920 	 * Try to combine buddies starting with a buddy size of 1
3921 	 * (i.e. two leaves). At a buddy size of 1 two buddy leaves
3922 	 * can be combined if both buddies have a maximum free of l2min;
3923 	 * the combination will result in the left-most buddy leaf having
3924 	 * a maximum free of l2min+1.
3925 	 * After processing all buddies for a given size, process buddies
3926 	 * at the next higher buddy size (i.e. current size * 2) and
3927 	 * the next maximum free (current free + 1).
3928 	 * This continues until the maximum possible buddy combination
3929 	 * yields maximum free.
3930 	 */
3931 	for (l2free = dtp->budmin, bsize = 1; l2free < l2max;
3932 	     l2free++, bsize = nextb) {
3933 		/* get next buddy size == current buddy pair size */
3934 		nextb = bsize << 1;
3935 
3936 		/* scan each adjacent buddy pair at current buddy size */
3937 		for (i = 0, cp = tp + le32_to_cpu(dtp->leafidx);
3938 		     i < le32_to_cpu(dtp->nleafs);
3939 		     i += nextb, cp += nextb) {
3940 			/* coalesce if both adjacent buddies are max free */
3941 			if (*cp == l2free && *(cp + bsize) == l2free) {
3942 				*cp = l2free + 1;	/* left take right */
3943 				*(cp + bsize) = -1;	/* right give left */
3944 			}
3945 		}
3946 	}
3947 
3948 	/*
3949 	 * bubble summary information of leaves up the tree.
3950 	 *
3951 	 * Starting at the leaf node level, the four nodes described by
3952 	 * the higher level parent node are compared for a maximum free and
3953 	 * this maximum becomes the value of the parent node.
3954 	 * when all lower level nodes are processed in this fashion then
3955 	 * move up to the next level (parent becomes a lower level node) and
3956 	 * continue the process for that level.
3957 	 */
3958 	for (child = le32_to_cpu(dtp->leafidx),
3959 	     nparent = le32_to_cpu(dtp->nleafs) >> 2;
3960 	     nparent > 0; nparent >>= 2, child = parent) {
3961 		/* get index of 1st node of parent level */
3962 		parent = (child - 1) >> 2;
3963 
3964 		/* set the value of the parent node as the maximum
3965 		 * of the four nodes of the current level.
3966 		 */
3967 		for (i = 0, cp = tp + child, cp1 = tp + parent;
3968 		     i < nparent; i++, cp += 4, cp1++)
3969 			*cp1 = TREEMAX(cp);
3970 	}
3971 
3972 	return (*tp);
3973 }
3974 
3975 
3976 /*
3977  *	dbInitDmapCtl()
3978  *
3979  * function: initialize dmapctl page
3980  */
dbInitDmapCtl(struct dmapctl * dcp,int level,int i)3981 static int dbInitDmapCtl(struct dmapctl * dcp, int level, int i)
3982 {				/* start leaf index not covered by range */
3983 	s8 *cp;
3984 
3985 	dcp->nleafs = cpu_to_le32(LPERCTL);
3986 	dcp->l2nleafs = cpu_to_le32(L2LPERCTL);
3987 	dcp->leafidx = cpu_to_le32(CTLLEAFIND);
3988 	dcp->height = cpu_to_le32(5);
3989 	dcp->budmin = L2BPERDMAP + L2LPERCTL * level;
3990 
3991 	/*
3992 	 * initialize the leaves of current level that were not covered
3993 	 * by the specified input block range (i.e. the leaves have no
3994 	 * low level dmapctl or dmap).
3995 	 */
3996 	cp = &dcp->stree[CTLLEAFIND + i];
3997 	for (; i < LPERCTL; i++)
3998 		*cp++ = NOFREE;
3999 
4000 	/* build the dmap's binary buddy summary tree */
4001 	return (dbInitTree((struct dmaptree *) dcp));
4002 }
4003 
4004 
4005 /*
4006  * NAME:	dbGetL2AGSize()/ujfs_getagl2size()
4007  *
4008  * FUNCTION:	Determine log2(allocation group size) from aggregate size
4009  *
4010  * PARAMETERS:
4011  *	nblocks	- Number of blocks in aggregate
4012  *
4013  * RETURNS: log2(allocation group size) in aggregate blocks
4014  */
dbGetL2AGSize(s64 nblocks)4015 static int dbGetL2AGSize(s64 nblocks)
4016 {
4017 	s64 sz;
4018 	s64 m;
4019 	int l2sz;
4020 
4021 	if (nblocks < BPERDMAP * MAXAG)
4022 		return (L2BPERDMAP);
4023 
4024 	/* round up aggregate size to power of 2 */
4025 	m = ((u64) 1 << (64 - 1));
4026 	for (l2sz = 64; l2sz >= 0; l2sz--, m >>= 1) {
4027 		if (m & nblocks)
4028 			break;
4029 	}
4030 
4031 	sz = (s64) 1 << l2sz;
4032 	if (sz < nblocks)
4033 		l2sz += 1;
4034 
4035 	/* agsize = roundupSize/max_number_of_ag */
4036 	return (l2sz - L2MAXAG);
4037 }
4038 
4039 
4040 /*
4041  * NAME:	dbMapFileSizeToMapSize()
4042  *
4043  * FUNCTION:	compute number of blocks the block allocation map file
4044  *		can cover from the map file size;
4045  *
4046  * RETURNS:	Number of blocks which can be covered by this block map file;
4047  */
4048 
4049 /*
4050  * maximum number of map pages at each level including control pages
4051  */
4052 #define MAXL0PAGES	(1 + LPERCTL)
4053 #define MAXL1PAGES	(1 + LPERCTL * MAXL0PAGES)
4054 
4055 /*
4056  * convert number of map pages to the zero origin top dmapctl level
4057  */
4058 #define BMAPPGTOLEV(npages)	\
4059 	(((npages) <= 3 + MAXL0PAGES) ? 0 : \
4060 	 ((npages) <= 2 + MAXL1PAGES) ? 1 : 2)
4061 
dbMapFileSizeToMapSize(struct inode * ipbmap)4062 s64 dbMapFileSizeToMapSize(struct inode * ipbmap)
4063 {
4064 	struct super_block *sb = ipbmap->i_sb;
4065 	s64 nblocks;
4066 	s64 npages, ndmaps;
4067 	int level, i;
4068 	int complete, factor;
4069 
4070 	nblocks = ipbmap->i_size >> JFS_SBI(sb)->l2bsize;
4071 	npages = nblocks >> JFS_SBI(sb)->l2nbperpage;
4072 	level = BMAPPGTOLEV(npages);
4073 
4074 	/* At each level, accumulate the number of dmap pages covered by
4075 	 * the number of full child levels below it;
4076 	 * repeat for the last incomplete child level.
4077 	 */
4078 	ndmaps = 0;
4079 	npages--;		/* skip the first global control page */
4080 	/* skip higher level control pages above top level covered by map */
4081 	npages -= (2 - level);
4082 	npages--;		/* skip top level's control page */
4083 	for (i = level; i >= 0; i--) {
4084 		factor =
4085 		    (i == 2) ? MAXL1PAGES : ((i == 1) ? MAXL0PAGES : 1);
4086 		complete = (u32) npages / factor;
4087 		ndmaps += complete * ((i == 2) ? LPERCTL * LPERCTL :
4088 				      ((i == 1) ? LPERCTL : 1));
4089 
4090 		/* pages in last/incomplete child */
4091 		npages = (u32) npages % factor;
4092 		/* skip incomplete child's level control page */
4093 		npages--;
4094 	}
4095 
4096 	/* convert the number of dmaps into the number of blocks
4097 	 * which can be covered by the dmaps;
4098 	 */
4099 	nblocks = ndmaps << L2BPERDMAP;
4100 
4101 	return (nblocks);
4102 }
4103