Linux Audio

Check our new training course

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