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