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