[XFS] Move compat ioctl structs & numbers into xfs_ioctl32.h
[safe/jmp/linux-2.6] / fs / xfs / xfs_log_recover.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_types.h"
21 #include "xfs_bit.h"
22 #include "xfs_log.h"
23 #include "xfs_inum.h"
24 #include "xfs_trans.h"
25 #include "xfs_sb.h"
26 #include "xfs_ag.h"
27 #include "xfs_dir2.h"
28 #include "xfs_dmapi.h"
29 #include "xfs_mount.h"
30 #include "xfs_error.h"
31 #include "xfs_bmap_btree.h"
32 #include "xfs_alloc_btree.h"
33 #include "xfs_ialloc_btree.h"
34 #include "xfs_dir2_sf.h"
35 #include "xfs_attr_sf.h"
36 #include "xfs_dinode.h"
37 #include "xfs_inode.h"
38 #include "xfs_inode_item.h"
39 #include "xfs_alloc.h"
40 #include "xfs_ialloc.h"
41 #include "xfs_log_priv.h"
42 #include "xfs_buf_item.h"
43 #include "xfs_log_recover.h"
44 #include "xfs_extfree_item.h"
45 #include "xfs_trans_priv.h"
46 #include "xfs_quota.h"
47 #include "xfs_rw.h"
48 #include "xfs_utils.h"
49
50 STATIC int      xlog_find_zeroed(xlog_t *, xfs_daddr_t *);
51 STATIC int      xlog_clear_stale_blocks(xlog_t *, xfs_lsn_t);
52 STATIC void     xlog_recover_insert_item_backq(xlog_recover_item_t **q,
53                                                xlog_recover_item_t *item);
54 #if defined(DEBUG)
55 STATIC void     xlog_recover_check_summary(xlog_t *);
56 #else
57 #define xlog_recover_check_summary(log)
58 #endif
59
60
61 /*
62  * Sector aligned buffer routines for buffer create/read/write/access
63  */
64
65 #define XLOG_SECTOR_ROUNDUP_BBCOUNT(log, bbs)   \
66         ( ((log)->l_sectbb_mask && (bbs & (log)->l_sectbb_mask)) ? \
67         ((bbs + (log)->l_sectbb_mask + 1) & ~(log)->l_sectbb_mask) : (bbs) )
68 #define XLOG_SECTOR_ROUNDDOWN_BLKNO(log, bno)   ((bno) & ~(log)->l_sectbb_mask)
69
70 xfs_buf_t *
71 xlog_get_bp(
72         xlog_t          *log,
73         int             num_bblks)
74 {
75         ASSERT(num_bblks > 0);
76
77         if (log->l_sectbb_log) {
78                 if (num_bblks > 1)
79                         num_bblks += XLOG_SECTOR_ROUNDUP_BBCOUNT(log, 1);
80                 num_bblks = XLOG_SECTOR_ROUNDUP_BBCOUNT(log, num_bblks);
81         }
82         return xfs_buf_get_noaddr(BBTOB(num_bblks), log->l_mp->m_logdev_targp);
83 }
84
85 void
86 xlog_put_bp(
87         xfs_buf_t       *bp)
88 {
89         xfs_buf_free(bp);
90 }
91
92
93 /*
94  * nbblks should be uint, but oh well.  Just want to catch that 32-bit length.
95  */
96 int
97 xlog_bread(
98         xlog_t          *log,
99         xfs_daddr_t     blk_no,
100         int             nbblks,
101         xfs_buf_t       *bp)
102 {
103         int             error;
104
105         if (log->l_sectbb_log) {
106                 blk_no = XLOG_SECTOR_ROUNDDOWN_BLKNO(log, blk_no);
107                 nbblks = XLOG_SECTOR_ROUNDUP_BBCOUNT(log, nbblks);
108         }
109
110         ASSERT(nbblks > 0);
111         ASSERT(BBTOB(nbblks) <= XFS_BUF_SIZE(bp));
112         ASSERT(bp);
113
114         XFS_BUF_SET_ADDR(bp, log->l_logBBstart + blk_no);
115         XFS_BUF_READ(bp);
116         XFS_BUF_BUSY(bp);
117         XFS_BUF_SET_COUNT(bp, BBTOB(nbblks));
118         XFS_BUF_SET_TARGET(bp, log->l_mp->m_logdev_targp);
119
120         xfsbdstrat(log->l_mp, bp);
121         error = xfs_iowait(bp);
122         if (error)
123                 xfs_ioerror_alert("xlog_bread", log->l_mp,
124                                   bp, XFS_BUF_ADDR(bp));
125         return error;
126 }
127
128 /*
129  * Write out the buffer at the given block for the given number of blocks.
130  * The buffer is kept locked across the write and is returned locked.
131  * This can only be used for synchronous log writes.
132  */
133 STATIC int
134 xlog_bwrite(
135         xlog_t          *log,
136         xfs_daddr_t     blk_no,
137         int             nbblks,
138         xfs_buf_t       *bp)
139 {
140         int             error;
141
142         if (log->l_sectbb_log) {
143                 blk_no = XLOG_SECTOR_ROUNDDOWN_BLKNO(log, blk_no);
144                 nbblks = XLOG_SECTOR_ROUNDUP_BBCOUNT(log, nbblks);
145         }
146
147         ASSERT(nbblks > 0);
148         ASSERT(BBTOB(nbblks) <= XFS_BUF_SIZE(bp));
149
150         XFS_BUF_SET_ADDR(bp, log->l_logBBstart + blk_no);
151         XFS_BUF_ZEROFLAGS(bp);
152         XFS_BUF_BUSY(bp);
153         XFS_BUF_HOLD(bp);
154         XFS_BUF_PSEMA(bp, PRIBIO);
155         XFS_BUF_SET_COUNT(bp, BBTOB(nbblks));
156         XFS_BUF_SET_TARGET(bp, log->l_mp->m_logdev_targp);
157
158         if ((error = xfs_bwrite(log->l_mp, bp)))
159                 xfs_ioerror_alert("xlog_bwrite", log->l_mp,
160                                   bp, XFS_BUF_ADDR(bp));
161         return error;
162 }
163
164 STATIC xfs_caddr_t
165 xlog_align(
166         xlog_t          *log,
167         xfs_daddr_t     blk_no,
168         int             nbblks,
169         xfs_buf_t       *bp)
170 {
171         xfs_caddr_t     ptr;
172
173         if (!log->l_sectbb_log)
174                 return XFS_BUF_PTR(bp);
175
176         ptr = XFS_BUF_PTR(bp) + BBTOB((int)blk_no & log->l_sectbb_mask);
177         ASSERT(XFS_BUF_SIZE(bp) >=
178                 BBTOB(nbblks + (blk_no & log->l_sectbb_mask)));
179         return ptr;
180 }
181
182 #ifdef DEBUG
183 /*
184  * dump debug superblock and log record information
185  */
186 STATIC void
187 xlog_header_check_dump(
188         xfs_mount_t             *mp,
189         xlog_rec_header_t       *head)
190 {
191         int                     b;
192
193         cmn_err(CE_DEBUG, "%s:  SB : uuid = ", __func__);
194         for (b = 0; b < 16; b++)
195                 cmn_err(CE_DEBUG, "%02x", ((uchar_t *)&mp->m_sb.sb_uuid)[b]);
196         cmn_err(CE_DEBUG, ", fmt = %d\n", XLOG_FMT);
197         cmn_err(CE_DEBUG, "    log : uuid = ");
198         for (b = 0; b < 16; b++)
199                 cmn_err(CE_DEBUG, "%02x",((uchar_t *)&head->h_fs_uuid)[b]);
200         cmn_err(CE_DEBUG, ", fmt = %d\n", be32_to_cpu(head->h_fmt));
201 }
202 #else
203 #define xlog_header_check_dump(mp, head)
204 #endif
205
206 /*
207  * check log record header for recovery
208  */
209 STATIC int
210 xlog_header_check_recover(
211         xfs_mount_t             *mp,
212         xlog_rec_header_t       *head)
213 {
214         ASSERT(be32_to_cpu(head->h_magicno) == XLOG_HEADER_MAGIC_NUM);
215
216         /*
217          * IRIX doesn't write the h_fmt field and leaves it zeroed
218          * (XLOG_FMT_UNKNOWN). This stops us from trying to recover
219          * a dirty log created in IRIX.
220          */
221         if (unlikely(be32_to_cpu(head->h_fmt) != XLOG_FMT)) {
222                 xlog_warn(
223         "XFS: dirty log written in incompatible format - can't recover");
224                 xlog_header_check_dump(mp, head);
225                 XFS_ERROR_REPORT("xlog_header_check_recover(1)",
226                                  XFS_ERRLEVEL_HIGH, mp);
227                 return XFS_ERROR(EFSCORRUPTED);
228         } else if (unlikely(!uuid_equal(&mp->m_sb.sb_uuid, &head->h_fs_uuid))) {
229                 xlog_warn(
230         "XFS: dirty log entry has mismatched uuid - can't recover");
231                 xlog_header_check_dump(mp, head);
232                 XFS_ERROR_REPORT("xlog_header_check_recover(2)",
233                                  XFS_ERRLEVEL_HIGH, mp);
234                 return XFS_ERROR(EFSCORRUPTED);
235         }
236         return 0;
237 }
238
239 /*
240  * read the head block of the log and check the header
241  */
242 STATIC int
243 xlog_header_check_mount(
244         xfs_mount_t             *mp,
245         xlog_rec_header_t       *head)
246 {
247         ASSERT(be32_to_cpu(head->h_magicno) == XLOG_HEADER_MAGIC_NUM);
248
249         if (uuid_is_nil(&head->h_fs_uuid)) {
250                 /*
251                  * IRIX doesn't write the h_fs_uuid or h_fmt fields. If
252                  * h_fs_uuid is nil, we assume this log was last mounted
253                  * by IRIX and continue.
254                  */
255                 xlog_warn("XFS: nil uuid in log - IRIX style log");
256         } else if (unlikely(!uuid_equal(&mp->m_sb.sb_uuid, &head->h_fs_uuid))) {
257                 xlog_warn("XFS: log has mismatched uuid - can't recover");
258                 xlog_header_check_dump(mp, head);
259                 XFS_ERROR_REPORT("xlog_header_check_mount",
260                                  XFS_ERRLEVEL_HIGH, mp);
261                 return XFS_ERROR(EFSCORRUPTED);
262         }
263         return 0;
264 }
265
266 STATIC void
267 xlog_recover_iodone(
268         struct xfs_buf  *bp)
269 {
270         xfs_mount_t     *mp;
271
272         ASSERT(XFS_BUF_FSPRIVATE(bp, void *));
273
274         if (XFS_BUF_GETERROR(bp)) {
275                 /*
276                  * We're not going to bother about retrying
277                  * this during recovery. One strike!
278                  */
279                 mp = XFS_BUF_FSPRIVATE(bp, xfs_mount_t *);
280                 xfs_ioerror_alert("xlog_recover_iodone",
281                                   mp, bp, XFS_BUF_ADDR(bp));
282                 xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
283         }
284         XFS_BUF_SET_FSPRIVATE(bp, NULL);
285         XFS_BUF_CLR_IODONE_FUNC(bp);
286         xfs_biodone(bp);
287 }
288
289 /*
290  * This routine finds (to an approximation) the first block in the physical
291  * log which contains the given cycle.  It uses a binary search algorithm.
292  * Note that the algorithm can not be perfect because the disk will not
293  * necessarily be perfect.
294  */
295 STATIC int
296 xlog_find_cycle_start(
297         xlog_t          *log,
298         xfs_buf_t       *bp,
299         xfs_daddr_t     first_blk,
300         xfs_daddr_t     *last_blk,
301         uint            cycle)
302 {
303         xfs_caddr_t     offset;
304         xfs_daddr_t     mid_blk;
305         uint            mid_cycle;
306         int             error;
307
308         mid_blk = BLK_AVG(first_blk, *last_blk);
309         while (mid_blk != first_blk && mid_blk != *last_blk) {
310                 if ((error = xlog_bread(log, mid_blk, 1, bp)))
311                         return error;
312                 offset = xlog_align(log, mid_blk, 1, bp);
313                 mid_cycle = xlog_get_cycle(offset);
314                 if (mid_cycle == cycle) {
315                         *last_blk = mid_blk;
316                         /* last_half_cycle == mid_cycle */
317                 } else {
318                         first_blk = mid_blk;
319                         /* first_half_cycle == mid_cycle */
320                 }
321                 mid_blk = BLK_AVG(first_blk, *last_blk);
322         }
323         ASSERT((mid_blk == first_blk && mid_blk+1 == *last_blk) ||
324                (mid_blk == *last_blk && mid_blk-1 == first_blk));
325
326         return 0;
327 }
328
329 /*
330  * Check that the range of blocks does not contain the cycle number
331  * given.  The scan needs to occur from front to back and the ptr into the
332  * region must be updated since a later routine will need to perform another
333  * test.  If the region is completely good, we end up returning the same
334  * last block number.
335  *
336  * Set blkno to -1 if we encounter no errors.  This is an invalid block number
337  * since we don't ever expect logs to get this large.
338  */
339 STATIC int
340 xlog_find_verify_cycle(
341         xlog_t          *log,
342         xfs_daddr_t     start_blk,
343         int             nbblks,
344         uint            stop_on_cycle_no,
345         xfs_daddr_t     *new_blk)
346 {
347         xfs_daddr_t     i, j;
348         uint            cycle;
349         xfs_buf_t       *bp;
350         xfs_daddr_t     bufblks;
351         xfs_caddr_t     buf = NULL;
352         int             error = 0;
353
354         bufblks = 1 << ffs(nbblks);
355
356         while (!(bp = xlog_get_bp(log, bufblks))) {
357                 /* can't get enough memory to do everything in one big buffer */
358                 bufblks >>= 1;
359                 if (bufblks <= log->l_sectbb_log)
360                         return ENOMEM;
361         }
362
363         for (i = start_blk; i < start_blk + nbblks; i += bufblks) {
364                 int     bcount;
365
366                 bcount = min(bufblks, (start_blk + nbblks - i));
367
368                 if ((error = xlog_bread(log, i, bcount, bp)))
369                         goto out;
370
371                 buf = xlog_align(log, i, bcount, bp);
372                 for (j = 0; j < bcount; j++) {
373                         cycle = xlog_get_cycle(buf);
374                         if (cycle == stop_on_cycle_no) {
375                                 *new_blk = i+j;
376                                 goto out;
377                         }
378
379                         buf += BBSIZE;
380                 }
381         }
382
383         *new_blk = -1;
384
385 out:
386         xlog_put_bp(bp);
387         return error;
388 }
389
390 /*
391  * Potentially backup over partial log record write.
392  *
393  * In the typical case, last_blk is the number of the block directly after
394  * a good log record.  Therefore, we subtract one to get the block number
395  * of the last block in the given buffer.  extra_bblks contains the number
396  * of blocks we would have read on a previous read.  This happens when the
397  * last log record is split over the end of the physical log.
398  *
399  * extra_bblks is the number of blocks potentially verified on a previous
400  * call to this routine.
401  */
402 STATIC int
403 xlog_find_verify_log_record(
404         xlog_t                  *log,
405         xfs_daddr_t             start_blk,
406         xfs_daddr_t             *last_blk,
407         int                     extra_bblks)
408 {
409         xfs_daddr_t             i;
410         xfs_buf_t               *bp;
411         xfs_caddr_t             offset = NULL;
412         xlog_rec_header_t       *head = NULL;
413         int                     error = 0;
414         int                     smallmem = 0;
415         int                     num_blks = *last_blk - start_blk;
416         int                     xhdrs;
417
418         ASSERT(start_blk != 0 || *last_blk != start_blk);
419
420         if (!(bp = xlog_get_bp(log, num_blks))) {
421                 if (!(bp = xlog_get_bp(log, 1)))
422                         return ENOMEM;
423                 smallmem = 1;
424         } else {
425                 if ((error = xlog_bread(log, start_blk, num_blks, bp)))
426                         goto out;
427                 offset = xlog_align(log, start_blk, num_blks, bp);
428                 offset += ((num_blks - 1) << BBSHIFT);
429         }
430
431         for (i = (*last_blk) - 1; i >= 0; i--) {
432                 if (i < start_blk) {
433                         /* valid log record not found */
434                         xlog_warn(
435                 "XFS: Log inconsistent (didn't find previous header)");
436                         ASSERT(0);
437                         error = XFS_ERROR(EIO);
438                         goto out;
439                 }
440
441                 if (smallmem) {
442                         if ((error = xlog_bread(log, i, 1, bp)))
443                                 goto out;
444                         offset = xlog_align(log, i, 1, bp);
445                 }
446
447                 head = (xlog_rec_header_t *)offset;
448
449                 if (XLOG_HEADER_MAGIC_NUM == be32_to_cpu(head->h_magicno))
450                         break;
451
452                 if (!smallmem)
453                         offset -= BBSIZE;
454         }
455
456         /*
457          * We hit the beginning of the physical log & still no header.  Return
458          * to caller.  If caller can handle a return of -1, then this routine
459          * will be called again for the end of the physical log.
460          */
461         if (i == -1) {
462                 error = -1;
463                 goto out;
464         }
465
466         /*
467          * We have the final block of the good log (the first block
468          * of the log record _before_ the head. So we check the uuid.
469          */
470         if ((error = xlog_header_check_mount(log->l_mp, head)))
471                 goto out;
472
473         /*
474          * We may have found a log record header before we expected one.
475          * last_blk will be the 1st block # with a given cycle #.  We may end
476          * up reading an entire log record.  In this case, we don't want to
477          * reset last_blk.  Only when last_blk points in the middle of a log
478          * record do we update last_blk.
479          */
480         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) {
481                 uint    h_size = be32_to_cpu(head->h_size);
482
483                 xhdrs = h_size / XLOG_HEADER_CYCLE_SIZE;
484                 if (h_size % XLOG_HEADER_CYCLE_SIZE)
485                         xhdrs++;
486         } else {
487                 xhdrs = 1;
488         }
489
490         if (*last_blk - i + extra_bblks !=
491             BTOBB(be32_to_cpu(head->h_len)) + xhdrs)
492                 *last_blk = i;
493
494 out:
495         xlog_put_bp(bp);
496         return error;
497 }
498
499 /*
500  * Head is defined to be the point of the log where the next log write
501  * write could go.  This means that incomplete LR writes at the end are
502  * eliminated when calculating the head.  We aren't guaranteed that previous
503  * LR have complete transactions.  We only know that a cycle number of
504  * current cycle number -1 won't be present in the log if we start writing
505  * from our current block number.
506  *
507  * last_blk contains the block number of the first block with a given
508  * cycle number.
509  *
510  * Return: zero if normal, non-zero if error.
511  */
512 STATIC int
513 xlog_find_head(
514         xlog_t          *log,
515         xfs_daddr_t     *return_head_blk)
516 {
517         xfs_buf_t       *bp;
518         xfs_caddr_t     offset;
519         xfs_daddr_t     new_blk, first_blk, start_blk, last_blk, head_blk;
520         int             num_scan_bblks;
521         uint            first_half_cycle, last_half_cycle;
522         uint            stop_on_cycle;
523         int             error, log_bbnum = log->l_logBBsize;
524
525         /* Is the end of the log device zeroed? */
526         if ((error = xlog_find_zeroed(log, &first_blk)) == -1) {
527                 *return_head_blk = first_blk;
528
529                 /* Is the whole lot zeroed? */
530                 if (!first_blk) {
531                         /* Linux XFS shouldn't generate totally zeroed logs -
532                          * mkfs etc write a dummy unmount record to a fresh
533                          * log so we can store the uuid in there
534                          */
535                         xlog_warn("XFS: totally zeroed log");
536                 }
537
538                 return 0;
539         } else if (error) {
540                 xlog_warn("XFS: empty log check failed");
541                 return error;
542         }
543
544         first_blk = 0;                  /* get cycle # of 1st block */
545         bp = xlog_get_bp(log, 1);
546         if (!bp)
547                 return ENOMEM;
548         if ((error = xlog_bread(log, 0, 1, bp)))
549                 goto bp_err;
550         offset = xlog_align(log, 0, 1, bp);
551         first_half_cycle = xlog_get_cycle(offset);
552
553         last_blk = head_blk = log_bbnum - 1;    /* get cycle # of last block */
554         if ((error = xlog_bread(log, last_blk, 1, bp)))
555                 goto bp_err;
556         offset = xlog_align(log, last_blk, 1, bp);
557         last_half_cycle = xlog_get_cycle(offset);
558         ASSERT(last_half_cycle != 0);
559
560         /*
561          * If the 1st half cycle number is equal to the last half cycle number,
562          * then the entire log is stamped with the same cycle number.  In this
563          * case, head_blk can't be set to zero (which makes sense).  The below
564          * math doesn't work out properly with head_blk equal to zero.  Instead,
565          * we set it to log_bbnum which is an invalid block number, but this
566          * value makes the math correct.  If head_blk doesn't changed through
567          * all the tests below, *head_blk is set to zero at the very end rather
568          * than log_bbnum.  In a sense, log_bbnum and zero are the same block
569          * in a circular file.
570          */
571         if (first_half_cycle == last_half_cycle) {
572                 /*
573                  * In this case we believe that the entire log should have
574                  * cycle number last_half_cycle.  We need to scan backwards
575                  * from the end verifying that there are no holes still
576                  * containing last_half_cycle - 1.  If we find such a hole,
577                  * then the start of that hole will be the new head.  The
578                  * simple case looks like
579                  *        x | x ... | x - 1 | x
580                  * Another case that fits this picture would be
581                  *        x | x + 1 | x ... | x
582                  * In this case the head really is somewhere at the end of the
583                  * log, as one of the latest writes at the beginning was
584                  * incomplete.
585                  * One more case is
586                  *        x | x + 1 | x ... | x - 1 | x
587                  * This is really the combination of the above two cases, and
588                  * the head has to end up at the start of the x-1 hole at the
589                  * end of the log.
590                  *
591                  * In the 256k log case, we will read from the beginning to the
592                  * end of the log and search for cycle numbers equal to x-1.
593                  * We don't worry about the x+1 blocks that we encounter,
594                  * because we know that they cannot be the head since the log
595                  * started with x.
596                  */
597                 head_blk = log_bbnum;
598                 stop_on_cycle = last_half_cycle - 1;
599         } else {
600                 /*
601                  * In this case we want to find the first block with cycle
602                  * number matching last_half_cycle.  We expect the log to be
603                  * some variation on
604                  *        x + 1 ... | x ...
605                  * The first block with cycle number x (last_half_cycle) will
606                  * be where the new head belongs.  First we do a binary search
607                  * for the first occurrence of last_half_cycle.  The binary
608                  * search may not be totally accurate, so then we scan back
609                  * from there looking for occurrences of last_half_cycle before
610                  * us.  If that backwards scan wraps around the beginning of
611                  * the log, then we look for occurrences of last_half_cycle - 1
612                  * at the end of the log.  The cases we're looking for look
613                  * like
614                  *        x + 1 ... | x | x + 1 | x ...
615                  *                               ^ binary search stopped here
616                  * or
617                  *        x + 1 ... | x ... | x - 1 | x
618                  *        <---------> less than scan distance
619                  */
620                 stop_on_cycle = last_half_cycle;
621                 if ((error = xlog_find_cycle_start(log, bp, first_blk,
622                                                 &head_blk, last_half_cycle)))
623                         goto bp_err;
624         }
625
626         /*
627          * Now validate the answer.  Scan back some number of maximum possible
628          * blocks and make sure each one has the expected cycle number.  The
629          * maximum is determined by the total possible amount of buffering
630          * in the in-core log.  The following number can be made tighter if
631          * we actually look at the block size of the filesystem.
632          */
633         num_scan_bblks = XLOG_TOTAL_REC_SHIFT(log);
634         if (head_blk >= num_scan_bblks) {
635                 /*
636                  * We are guaranteed that the entire check can be performed
637                  * in one buffer.
638                  */
639                 start_blk = head_blk - num_scan_bblks;
640                 if ((error = xlog_find_verify_cycle(log,
641                                                 start_blk, num_scan_bblks,
642                                                 stop_on_cycle, &new_blk)))
643                         goto bp_err;
644                 if (new_blk != -1)
645                         head_blk = new_blk;
646         } else {                /* need to read 2 parts of log */
647                 /*
648                  * We are going to scan backwards in the log in two parts.
649                  * First we scan the physical end of the log.  In this part
650                  * of the log, we are looking for blocks with cycle number
651                  * last_half_cycle - 1.
652                  * If we find one, then we know that the log starts there, as
653                  * we've found a hole that didn't get written in going around
654                  * the end of the physical log.  The simple case for this is
655                  *        x + 1 ... | x ... | x - 1 | x
656                  *        <---------> less than scan distance
657                  * If all of the blocks at the end of the log have cycle number
658                  * last_half_cycle, then we check the blocks at the start of
659                  * the log looking for occurrences of last_half_cycle.  If we
660                  * find one, then our current estimate for the location of the
661                  * first occurrence of last_half_cycle is wrong and we move
662                  * back to the hole we've found.  This case looks like
663                  *        x + 1 ... | x | x + 1 | x ...
664                  *                               ^ binary search stopped here
665                  * Another case we need to handle that only occurs in 256k
666                  * logs is
667                  *        x + 1 ... | x ... | x+1 | x ...
668                  *                   ^ binary search stops here
669                  * In a 256k log, the scan at the end of the log will see the
670                  * x + 1 blocks.  We need to skip past those since that is
671                  * certainly not the head of the log.  By searching for
672                  * last_half_cycle-1 we accomplish that.
673                  */
674                 start_blk = log_bbnum - num_scan_bblks + head_blk;
675                 ASSERT(head_blk <= INT_MAX &&
676                         (xfs_daddr_t) num_scan_bblks - head_blk >= 0);
677                 if ((error = xlog_find_verify_cycle(log, start_blk,
678                                         num_scan_bblks - (int)head_blk,
679                                         (stop_on_cycle - 1), &new_blk)))
680                         goto bp_err;
681                 if (new_blk != -1) {
682                         head_blk = new_blk;
683                         goto bad_blk;
684                 }
685
686                 /*
687                  * Scan beginning of log now.  The last part of the physical
688                  * log is good.  This scan needs to verify that it doesn't find
689                  * the last_half_cycle.
690                  */
691                 start_blk = 0;
692                 ASSERT(head_blk <= INT_MAX);
693                 if ((error = xlog_find_verify_cycle(log,
694                                         start_blk, (int)head_blk,
695                                         stop_on_cycle, &new_blk)))
696                         goto bp_err;
697                 if (new_blk != -1)
698                         head_blk = new_blk;
699         }
700
701  bad_blk:
702         /*
703          * Now we need to make sure head_blk is not pointing to a block in
704          * the middle of a log record.
705          */
706         num_scan_bblks = XLOG_REC_SHIFT(log);
707         if (head_blk >= num_scan_bblks) {
708                 start_blk = head_blk - num_scan_bblks; /* don't read head_blk */
709
710                 /* start ptr at last block ptr before head_blk */
711                 if ((error = xlog_find_verify_log_record(log, start_blk,
712                                                         &head_blk, 0)) == -1) {
713                         error = XFS_ERROR(EIO);
714                         goto bp_err;
715                 } else if (error)
716                         goto bp_err;
717         } else {
718                 start_blk = 0;
719                 ASSERT(head_blk <= INT_MAX);
720                 if ((error = xlog_find_verify_log_record(log, start_blk,
721                                                         &head_blk, 0)) == -1) {
722                         /* We hit the beginning of the log during our search */
723                         start_blk = log_bbnum - num_scan_bblks + head_blk;
724                         new_blk = log_bbnum;
725                         ASSERT(start_blk <= INT_MAX &&
726                                 (xfs_daddr_t) log_bbnum-start_blk >= 0);
727                         ASSERT(head_blk <= INT_MAX);
728                         if ((error = xlog_find_verify_log_record(log,
729                                                         start_blk, &new_blk,
730                                                         (int)head_blk)) == -1) {
731                                 error = XFS_ERROR(EIO);
732                                 goto bp_err;
733                         } else if (error)
734                                 goto bp_err;
735                         if (new_blk != log_bbnum)
736                                 head_blk = new_blk;
737                 } else if (error)
738                         goto bp_err;
739         }
740
741         xlog_put_bp(bp);
742         if (head_blk == log_bbnum)
743                 *return_head_blk = 0;
744         else
745                 *return_head_blk = head_blk;
746         /*
747          * When returning here, we have a good block number.  Bad block
748          * means that during a previous crash, we didn't have a clean break
749          * from cycle number N to cycle number N-1.  In this case, we need
750          * to find the first block with cycle number N-1.
751          */
752         return 0;
753
754  bp_err:
755         xlog_put_bp(bp);
756
757         if (error)
758             xlog_warn("XFS: failed to find log head");
759         return error;
760 }
761
762 /*
763  * Find the sync block number or the tail of the log.
764  *
765  * This will be the block number of the last record to have its
766  * associated buffers synced to disk.  Every log record header has
767  * a sync lsn embedded in it.  LSNs hold block numbers, so it is easy
768  * to get a sync block number.  The only concern is to figure out which
769  * log record header to believe.
770  *
771  * The following algorithm uses the log record header with the largest
772  * lsn.  The entire log record does not need to be valid.  We only care
773  * that the header is valid.
774  *
775  * We could speed up search by using current head_blk buffer, but it is not
776  * available.
777  */
778 int
779 xlog_find_tail(
780         xlog_t                  *log,
781         xfs_daddr_t             *head_blk,
782         xfs_daddr_t             *tail_blk)
783 {
784         xlog_rec_header_t       *rhead;
785         xlog_op_header_t        *op_head;
786         xfs_caddr_t             offset = NULL;
787         xfs_buf_t               *bp;
788         int                     error, i, found;
789         xfs_daddr_t             umount_data_blk;
790         xfs_daddr_t             after_umount_blk;
791         xfs_lsn_t               tail_lsn;
792         int                     hblks;
793
794         found = 0;
795
796         /*
797          * Find previous log record
798          */
799         if ((error = xlog_find_head(log, head_blk)))
800                 return error;
801
802         bp = xlog_get_bp(log, 1);
803         if (!bp)
804                 return ENOMEM;
805         if (*head_blk == 0) {                           /* special case */
806                 if ((error = xlog_bread(log, 0, 1, bp)))
807                         goto bread_err;
808                 offset = xlog_align(log, 0, 1, bp);
809                 if (xlog_get_cycle(offset) == 0) {
810                         *tail_blk = 0;
811                         /* leave all other log inited values alone */
812                         goto exit;
813                 }
814         }
815
816         /*
817          * Search backwards looking for log record header block
818          */
819         ASSERT(*head_blk < INT_MAX);
820         for (i = (int)(*head_blk) - 1; i >= 0; i--) {
821                 if ((error = xlog_bread(log, i, 1, bp)))
822                         goto bread_err;
823                 offset = xlog_align(log, i, 1, bp);
824                 if (XLOG_HEADER_MAGIC_NUM == be32_to_cpu(*(__be32 *)offset)) {
825                         found = 1;
826                         break;
827                 }
828         }
829         /*
830          * If we haven't found the log record header block, start looking
831          * again from the end of the physical log.  XXXmiken: There should be
832          * a check here to make sure we didn't search more than N blocks in
833          * the previous code.
834          */
835         if (!found) {
836                 for (i = log->l_logBBsize - 1; i >= (int)(*head_blk); i--) {
837                         if ((error = xlog_bread(log, i, 1, bp)))
838                                 goto bread_err;
839                         offset = xlog_align(log, i, 1, bp);
840                         if (XLOG_HEADER_MAGIC_NUM ==
841                             be32_to_cpu(*(__be32 *)offset)) {
842                                 found = 2;
843                                 break;
844                         }
845                 }
846         }
847         if (!found) {
848                 xlog_warn("XFS: xlog_find_tail: couldn't find sync record");
849                 ASSERT(0);
850                 return XFS_ERROR(EIO);
851         }
852
853         /* find blk_no of tail of log */
854         rhead = (xlog_rec_header_t *)offset;
855         *tail_blk = BLOCK_LSN(be64_to_cpu(rhead->h_tail_lsn));
856
857         /*
858          * Reset log values according to the state of the log when we
859          * crashed.  In the case where head_blk == 0, we bump curr_cycle
860          * one because the next write starts a new cycle rather than
861          * continuing the cycle of the last good log record.  At this
862          * point we have guaranteed that all partial log records have been
863          * accounted for.  Therefore, we know that the last good log record
864          * written was complete and ended exactly on the end boundary
865          * of the physical log.
866          */
867         log->l_prev_block = i;
868         log->l_curr_block = (int)*head_blk;
869         log->l_curr_cycle = be32_to_cpu(rhead->h_cycle);
870         if (found == 2)
871                 log->l_curr_cycle++;
872         log->l_tail_lsn = be64_to_cpu(rhead->h_tail_lsn);
873         log->l_last_sync_lsn = be64_to_cpu(rhead->h_lsn);
874         log->l_grant_reserve_cycle = log->l_curr_cycle;
875         log->l_grant_reserve_bytes = BBTOB(log->l_curr_block);
876         log->l_grant_write_cycle = log->l_curr_cycle;
877         log->l_grant_write_bytes = BBTOB(log->l_curr_block);
878
879         /*
880          * Look for unmount record.  If we find it, then we know there
881          * was a clean unmount.  Since 'i' could be the last block in
882          * the physical log, we convert to a log block before comparing
883          * to the head_blk.
884          *
885          * Save the current tail lsn to use to pass to
886          * xlog_clear_stale_blocks() below.  We won't want to clear the
887          * unmount record if there is one, so we pass the lsn of the
888          * unmount record rather than the block after it.
889          */
890         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) {
891                 int     h_size = be32_to_cpu(rhead->h_size);
892                 int     h_version = be32_to_cpu(rhead->h_version);
893
894                 if ((h_version & XLOG_VERSION_2) &&
895                     (h_size > XLOG_HEADER_CYCLE_SIZE)) {
896                         hblks = h_size / XLOG_HEADER_CYCLE_SIZE;
897                         if (h_size % XLOG_HEADER_CYCLE_SIZE)
898                                 hblks++;
899                 } else {
900                         hblks = 1;
901                 }
902         } else {
903                 hblks = 1;
904         }
905         after_umount_blk = (i + hblks + (int)
906                 BTOBB(be32_to_cpu(rhead->h_len))) % log->l_logBBsize;
907         tail_lsn = log->l_tail_lsn;
908         if (*head_blk == after_umount_blk &&
909             be32_to_cpu(rhead->h_num_logops) == 1) {
910                 umount_data_blk = (i + hblks) % log->l_logBBsize;
911                 if ((error = xlog_bread(log, umount_data_blk, 1, bp))) {
912                         goto bread_err;
913                 }
914                 offset = xlog_align(log, umount_data_blk, 1, bp);
915                 op_head = (xlog_op_header_t *)offset;
916                 if (op_head->oh_flags & XLOG_UNMOUNT_TRANS) {
917                         /*
918                          * Set tail and last sync so that newly written
919                          * log records will point recovery to after the
920                          * current unmount record.
921                          */
922                         log->l_tail_lsn =
923                                 xlog_assign_lsn(log->l_curr_cycle,
924                                                 after_umount_blk);
925                         log->l_last_sync_lsn =
926                                 xlog_assign_lsn(log->l_curr_cycle,
927                                                 after_umount_blk);
928                         *tail_blk = after_umount_blk;
929
930                         /*
931                          * Note that the unmount was clean. If the unmount
932                          * was not clean, we need to know this to rebuild the
933                          * superblock counters from the perag headers if we
934                          * have a filesystem using non-persistent counters.
935                          */
936                         log->l_mp->m_flags |= XFS_MOUNT_WAS_CLEAN;
937                 }
938         }
939
940         /*
941          * Make sure that there are no blocks in front of the head
942          * with the same cycle number as the head.  This can happen
943          * because we allow multiple outstanding log writes concurrently,
944          * and the later writes might make it out before earlier ones.
945          *
946          * We use the lsn from before modifying it so that we'll never
947          * overwrite the unmount record after a clean unmount.
948          *
949          * Do this only if we are going to recover the filesystem
950          *
951          * NOTE: This used to say "if (!readonly)"
952          * However on Linux, we can & do recover a read-only filesystem.
953          * We only skip recovery if NORECOVERY is specified on mount,
954          * in which case we would not be here.
955          *
956          * But... if the -device- itself is readonly, just skip this.
957          * We can't recover this device anyway, so it won't matter.
958          */
959         if (!xfs_readonly_buftarg(log->l_mp->m_logdev_targp)) {
960                 error = xlog_clear_stale_blocks(log, tail_lsn);
961         }
962
963 bread_err:
964 exit:
965         xlog_put_bp(bp);
966
967         if (error)
968                 xlog_warn("XFS: failed to locate log tail");
969         return error;
970 }
971
972 /*
973  * Is the log zeroed at all?
974  *
975  * The last binary search should be changed to perform an X block read
976  * once X becomes small enough.  You can then search linearly through
977  * the X blocks.  This will cut down on the number of reads we need to do.
978  *
979  * If the log is partially zeroed, this routine will pass back the blkno
980  * of the first block with cycle number 0.  It won't have a complete LR
981  * preceding it.
982  *
983  * Return:
984  *      0  => the log is completely written to
985  *      -1 => use *blk_no as the first block of the log
986  *      >0 => error has occurred
987  */
988 STATIC int
989 xlog_find_zeroed(
990         xlog_t          *log,
991         xfs_daddr_t     *blk_no)
992 {
993         xfs_buf_t       *bp;
994         xfs_caddr_t     offset;
995         uint            first_cycle, last_cycle;
996         xfs_daddr_t     new_blk, last_blk, start_blk;
997         xfs_daddr_t     num_scan_bblks;
998         int             error, log_bbnum = log->l_logBBsize;
999
1000         *blk_no = 0;
1001
1002         /* check totally zeroed log */
1003         bp = xlog_get_bp(log, 1);
1004         if (!bp)
1005                 return ENOMEM;
1006         if ((error = xlog_bread(log, 0, 1, bp)))
1007                 goto bp_err;
1008         offset = xlog_align(log, 0, 1, bp);
1009         first_cycle = xlog_get_cycle(offset);
1010         if (first_cycle == 0) {         /* completely zeroed log */
1011                 *blk_no = 0;
1012                 xlog_put_bp(bp);
1013                 return -1;
1014         }
1015
1016         /* check partially zeroed log */
1017         if ((error = xlog_bread(log, log_bbnum-1, 1, bp)))
1018                 goto bp_err;
1019         offset = xlog_align(log, log_bbnum-1, 1, bp);
1020         last_cycle = xlog_get_cycle(offset);
1021         if (last_cycle != 0) {          /* log completely written to */
1022                 xlog_put_bp(bp);
1023                 return 0;
1024         } else if (first_cycle != 1) {
1025                 /*
1026                  * If the cycle of the last block is zero, the cycle of
1027                  * the first block must be 1. If it's not, maybe we're
1028                  * not looking at a log... Bail out.
1029                  */
1030                 xlog_warn("XFS: Log inconsistent or not a log (last==0, first!=1)");
1031                 return XFS_ERROR(EINVAL);
1032         }
1033
1034         /* we have a partially zeroed log */
1035         last_blk = log_bbnum-1;
1036         if ((error = xlog_find_cycle_start(log, bp, 0, &last_blk, 0)))
1037                 goto bp_err;
1038
1039         /*
1040          * Validate the answer.  Because there is no way to guarantee that
1041          * the entire log is made up of log records which are the same size,
1042          * we scan over the defined maximum blocks.  At this point, the maximum
1043          * is not chosen to mean anything special.   XXXmiken
1044          */
1045         num_scan_bblks = XLOG_TOTAL_REC_SHIFT(log);
1046         ASSERT(num_scan_bblks <= INT_MAX);
1047
1048         if (last_blk < num_scan_bblks)
1049                 num_scan_bblks = last_blk;
1050         start_blk = last_blk - num_scan_bblks;
1051
1052         /*
1053          * We search for any instances of cycle number 0 that occur before
1054          * our current estimate of the head.  What we're trying to detect is
1055          *        1 ... | 0 | 1 | 0...
1056          *                       ^ binary search ends here
1057          */
1058         if ((error = xlog_find_verify_cycle(log, start_blk,
1059                                          (int)num_scan_bblks, 0, &new_blk)))
1060                 goto bp_err;
1061         if (new_blk != -1)
1062                 last_blk = new_blk;
1063
1064         /*
1065          * Potentially backup over partial log record write.  We don't need
1066          * to search the end of the log because we know it is zero.
1067          */
1068         if ((error = xlog_find_verify_log_record(log, start_blk,
1069                                 &last_blk, 0)) == -1) {
1070             error = XFS_ERROR(EIO);
1071             goto bp_err;
1072         } else if (error)
1073             goto bp_err;
1074
1075         *blk_no = last_blk;
1076 bp_err:
1077         xlog_put_bp(bp);
1078         if (error)
1079                 return error;
1080         return -1;
1081 }
1082
1083 /*
1084  * These are simple subroutines used by xlog_clear_stale_blocks() below
1085  * to initialize a buffer full of empty log record headers and write
1086  * them into the log.
1087  */
1088 STATIC void
1089 xlog_add_record(
1090         xlog_t                  *log,
1091         xfs_caddr_t             buf,
1092         int                     cycle,
1093         int                     block,
1094         int                     tail_cycle,
1095         int                     tail_block)
1096 {
1097         xlog_rec_header_t       *recp = (xlog_rec_header_t *)buf;
1098
1099         memset(buf, 0, BBSIZE);
1100         recp->h_magicno = cpu_to_be32(XLOG_HEADER_MAGIC_NUM);
1101         recp->h_cycle = cpu_to_be32(cycle);
1102         recp->h_version = cpu_to_be32(
1103                         xfs_sb_version_haslogv2(&log->l_mp->m_sb) ? 2 : 1);
1104         recp->h_lsn = cpu_to_be64(xlog_assign_lsn(cycle, block));
1105         recp->h_tail_lsn = cpu_to_be64(xlog_assign_lsn(tail_cycle, tail_block));
1106         recp->h_fmt = cpu_to_be32(XLOG_FMT);
1107         memcpy(&recp->h_fs_uuid, &log->l_mp->m_sb.sb_uuid, sizeof(uuid_t));
1108 }
1109
1110 STATIC int
1111 xlog_write_log_records(
1112         xlog_t          *log,
1113         int             cycle,
1114         int             start_block,
1115         int             blocks,
1116         int             tail_cycle,
1117         int             tail_block)
1118 {
1119         xfs_caddr_t     offset;
1120         xfs_buf_t       *bp;
1121         int             balign, ealign;
1122         int             sectbb = XLOG_SECTOR_ROUNDUP_BBCOUNT(log, 1);
1123         int             end_block = start_block + blocks;
1124         int             bufblks;
1125         int             error = 0;
1126         int             i, j = 0;
1127
1128         bufblks = 1 << ffs(blocks);
1129         while (!(bp = xlog_get_bp(log, bufblks))) {
1130                 bufblks >>= 1;
1131                 if (bufblks <= log->l_sectbb_log)
1132                         return ENOMEM;
1133         }
1134
1135         /* We may need to do a read at the start to fill in part of
1136          * the buffer in the starting sector not covered by the first
1137          * write below.
1138          */
1139         balign = XLOG_SECTOR_ROUNDDOWN_BLKNO(log, start_block);
1140         if (balign != start_block) {
1141                 if ((error = xlog_bread(log, start_block, 1, bp))) {
1142                         xlog_put_bp(bp);
1143                         return error;
1144                 }
1145                 j = start_block - balign;
1146         }
1147
1148         for (i = start_block; i < end_block; i += bufblks) {
1149                 int             bcount, endcount;
1150
1151                 bcount = min(bufblks, end_block - start_block);
1152                 endcount = bcount - j;
1153
1154                 /* We may need to do a read at the end to fill in part of
1155                  * the buffer in the final sector not covered by the write.
1156                  * If this is the same sector as the above read, skip it.
1157                  */
1158                 ealign = XLOG_SECTOR_ROUNDDOWN_BLKNO(log, end_block);
1159                 if (j == 0 && (start_block + endcount > ealign)) {
1160                         offset = XFS_BUF_PTR(bp);
1161                         balign = BBTOB(ealign - start_block);
1162                         error = XFS_BUF_SET_PTR(bp, offset + balign,
1163                                                 BBTOB(sectbb));
1164                         if (!error)
1165                                 error = xlog_bread(log, ealign, sectbb, bp);
1166                         if (!error)
1167                                 error = XFS_BUF_SET_PTR(bp, offset, bufblks);
1168                         if (error)
1169                                 break;
1170                 }
1171
1172                 offset = xlog_align(log, start_block, endcount, bp);
1173                 for (; j < endcount; j++) {
1174                         xlog_add_record(log, offset, cycle, i+j,
1175                                         tail_cycle, tail_block);
1176                         offset += BBSIZE;
1177                 }
1178                 error = xlog_bwrite(log, start_block, endcount, bp);
1179                 if (error)
1180                         break;
1181                 start_block += endcount;
1182                 j = 0;
1183         }
1184         xlog_put_bp(bp);
1185         return error;
1186 }
1187
1188 /*
1189  * This routine is called to blow away any incomplete log writes out
1190  * in front of the log head.  We do this so that we won't become confused
1191  * if we come up, write only a little bit more, and then crash again.
1192  * If we leave the partial log records out there, this situation could
1193  * cause us to think those partial writes are valid blocks since they
1194  * have the current cycle number.  We get rid of them by overwriting them
1195  * with empty log records with the old cycle number rather than the
1196  * current one.
1197  *
1198  * The tail lsn is passed in rather than taken from
1199  * the log so that we will not write over the unmount record after a
1200  * clean unmount in a 512 block log.  Doing so would leave the log without
1201  * any valid log records in it until a new one was written.  If we crashed
1202  * during that time we would not be able to recover.
1203  */
1204 STATIC int
1205 xlog_clear_stale_blocks(
1206         xlog_t          *log,
1207         xfs_lsn_t       tail_lsn)
1208 {
1209         int             tail_cycle, head_cycle;
1210         int             tail_block, head_block;
1211         int             tail_distance, max_distance;
1212         int             distance;
1213         int             error;
1214
1215         tail_cycle = CYCLE_LSN(tail_lsn);
1216         tail_block = BLOCK_LSN(tail_lsn);
1217         head_cycle = log->l_curr_cycle;
1218         head_block = log->l_curr_block;
1219
1220         /*
1221          * Figure out the distance between the new head of the log
1222          * and the tail.  We want to write over any blocks beyond the
1223          * head that we may have written just before the crash, but
1224          * we don't want to overwrite the tail of the log.
1225          */
1226         if (head_cycle == tail_cycle) {
1227                 /*
1228                  * The tail is behind the head in the physical log,
1229                  * so the distance from the head to the tail is the
1230                  * distance from the head to the end of the log plus
1231                  * the distance from the beginning of the log to the
1232                  * tail.
1233                  */
1234                 if (unlikely(head_block < tail_block || head_block >= log->l_logBBsize)) {
1235                         XFS_ERROR_REPORT("xlog_clear_stale_blocks(1)",
1236                                          XFS_ERRLEVEL_LOW, log->l_mp);
1237                         return XFS_ERROR(EFSCORRUPTED);
1238                 }
1239                 tail_distance = tail_block + (log->l_logBBsize - head_block);
1240         } else {
1241                 /*
1242                  * The head is behind the tail in the physical log,
1243                  * so the distance from the head to the tail is just
1244                  * the tail block minus the head block.
1245                  */
1246                 if (unlikely(head_block >= tail_block || head_cycle != (tail_cycle + 1))){
1247                         XFS_ERROR_REPORT("xlog_clear_stale_blocks(2)",
1248                                          XFS_ERRLEVEL_LOW, log->l_mp);
1249                         return XFS_ERROR(EFSCORRUPTED);
1250                 }
1251                 tail_distance = tail_block - head_block;
1252         }
1253
1254         /*
1255          * If the head is right up against the tail, we can't clear
1256          * anything.
1257          */
1258         if (tail_distance <= 0) {
1259                 ASSERT(tail_distance == 0);
1260                 return 0;
1261         }
1262
1263         max_distance = XLOG_TOTAL_REC_SHIFT(log);
1264         /*
1265          * Take the smaller of the maximum amount of outstanding I/O
1266          * we could have and the distance to the tail to clear out.
1267          * We take the smaller so that we don't overwrite the tail and
1268          * we don't waste all day writing from the head to the tail
1269          * for no reason.
1270          */
1271         max_distance = MIN(max_distance, tail_distance);
1272
1273         if ((head_block + max_distance) <= log->l_logBBsize) {
1274                 /*
1275                  * We can stomp all the blocks we need to without
1276                  * wrapping around the end of the log.  Just do it
1277                  * in a single write.  Use the cycle number of the
1278                  * current cycle minus one so that the log will look like:
1279                  *     n ... | n - 1 ...
1280                  */
1281                 error = xlog_write_log_records(log, (head_cycle - 1),
1282                                 head_block, max_distance, tail_cycle,
1283                                 tail_block);
1284                 if (error)
1285                         return error;
1286         } else {
1287                 /*
1288                  * We need to wrap around the end of the physical log in
1289                  * order to clear all the blocks.  Do it in two separate
1290                  * I/Os.  The first write should be from the head to the
1291                  * end of the physical log, and it should use the current
1292                  * cycle number minus one just like above.
1293                  */
1294                 distance = log->l_logBBsize - head_block;
1295                 error = xlog_write_log_records(log, (head_cycle - 1),
1296                                 head_block, distance, tail_cycle,
1297                                 tail_block);
1298
1299                 if (error)
1300                         return error;
1301
1302                 /*
1303                  * Now write the blocks at the start of the physical log.
1304                  * This writes the remainder of the blocks we want to clear.
1305                  * It uses the current cycle number since we're now on the
1306                  * same cycle as the head so that we get:
1307                  *    n ... n ... | n - 1 ...
1308                  *    ^^^^^ blocks we're writing
1309                  */
1310                 distance = max_distance - (log->l_logBBsize - head_block);
1311                 error = xlog_write_log_records(log, head_cycle, 0, distance,
1312                                 tail_cycle, tail_block);
1313                 if (error)
1314                         return error;
1315         }
1316
1317         return 0;
1318 }
1319
1320 /******************************************************************************
1321  *
1322  *              Log recover routines
1323  *
1324  ******************************************************************************
1325  */
1326
1327 STATIC xlog_recover_t *
1328 xlog_recover_find_tid(
1329         xlog_recover_t          *q,
1330         xlog_tid_t              tid)
1331 {
1332         xlog_recover_t          *p = q;
1333
1334         while (p != NULL) {
1335                 if (p->r_log_tid == tid)
1336                     break;
1337                 p = p->r_next;
1338         }
1339         return p;
1340 }
1341
1342 STATIC void
1343 xlog_recover_put_hashq(
1344         xlog_recover_t          **q,
1345         xlog_recover_t          *trans)
1346 {
1347         trans->r_next = *q;
1348         *q = trans;
1349 }
1350
1351 STATIC void
1352 xlog_recover_add_item(
1353         xlog_recover_item_t     **itemq)
1354 {
1355         xlog_recover_item_t     *item;
1356
1357         item = kmem_zalloc(sizeof(xlog_recover_item_t), KM_SLEEP);
1358         xlog_recover_insert_item_backq(itemq, item);
1359 }
1360
1361 STATIC int
1362 xlog_recover_add_to_cont_trans(
1363         xlog_recover_t          *trans,
1364         xfs_caddr_t             dp,
1365         int                     len)
1366 {
1367         xlog_recover_item_t     *item;
1368         xfs_caddr_t             ptr, old_ptr;
1369         int                     old_len;
1370
1371         item = trans->r_itemq;
1372         if (item == NULL) {
1373                 /* finish copying rest of trans header */
1374                 xlog_recover_add_item(&trans->r_itemq);
1375                 ptr = (xfs_caddr_t) &trans->r_theader +
1376                                 sizeof(xfs_trans_header_t) - len;
1377                 memcpy(ptr, dp, len); /* d, s, l */
1378                 return 0;
1379         }
1380         item = item->ri_prev;
1381
1382         old_ptr = item->ri_buf[item->ri_cnt-1].i_addr;
1383         old_len = item->ri_buf[item->ri_cnt-1].i_len;
1384
1385         ptr = kmem_realloc(old_ptr, len+old_len, old_len, 0u);
1386         memcpy(&ptr[old_len], dp, len); /* d, s, l */
1387         item->ri_buf[item->ri_cnt-1].i_len += len;
1388         item->ri_buf[item->ri_cnt-1].i_addr = ptr;
1389         return 0;
1390 }
1391
1392 /*
1393  * The next region to add is the start of a new region.  It could be
1394  * a whole region or it could be the first part of a new region.  Because
1395  * of this, the assumption here is that the type and size fields of all
1396  * format structures fit into the first 32 bits of the structure.
1397  *
1398  * This works because all regions must be 32 bit aligned.  Therefore, we
1399  * either have both fields or we have neither field.  In the case we have
1400  * neither field, the data part of the region is zero length.  We only have
1401  * a log_op_header and can throw away the header since a new one will appear
1402  * later.  If we have at least 4 bytes, then we can determine how many regions
1403  * will appear in the current log item.
1404  */
1405 STATIC int
1406 xlog_recover_add_to_trans(
1407         xlog_recover_t          *trans,
1408         xfs_caddr_t             dp,
1409         int                     len)
1410 {
1411         xfs_inode_log_format_t  *in_f;                  /* any will do */
1412         xlog_recover_item_t     *item;
1413         xfs_caddr_t             ptr;
1414
1415         if (!len)
1416                 return 0;
1417         item = trans->r_itemq;
1418         if (item == NULL) {
1419                 /* we need to catch log corruptions here */
1420                 if (*(uint *)dp != XFS_TRANS_HEADER_MAGIC) {
1421                         xlog_warn("XFS: xlog_recover_add_to_trans: "
1422                                   "bad header magic number");
1423                         ASSERT(0);
1424                         return XFS_ERROR(EIO);
1425                 }
1426                 if (len == sizeof(xfs_trans_header_t))
1427                         xlog_recover_add_item(&trans->r_itemq);
1428                 memcpy(&trans->r_theader, dp, len); /* d, s, l */
1429                 return 0;
1430         }
1431
1432         ptr = kmem_alloc(len, KM_SLEEP);
1433         memcpy(ptr, dp, len);
1434         in_f = (xfs_inode_log_format_t *)ptr;
1435
1436         if (item->ri_prev->ri_total != 0 &&
1437              item->ri_prev->ri_total == item->ri_prev->ri_cnt) {
1438                 xlog_recover_add_item(&trans->r_itemq);
1439         }
1440         item = trans->r_itemq;
1441         item = item->ri_prev;
1442
1443         if (item->ri_total == 0) {              /* first region to be added */
1444                 item->ri_total  = in_f->ilf_size;
1445                 ASSERT(item->ri_total <= XLOG_MAX_REGIONS_IN_ITEM);
1446                 item->ri_buf = kmem_zalloc((item->ri_total *
1447                                             sizeof(xfs_log_iovec_t)), KM_SLEEP);
1448         }
1449         ASSERT(item->ri_total > item->ri_cnt);
1450         /* Description region is ri_buf[0] */
1451         item->ri_buf[item->ri_cnt].i_addr = ptr;
1452         item->ri_buf[item->ri_cnt].i_len  = len;
1453         item->ri_cnt++;
1454         return 0;
1455 }
1456
1457 STATIC void
1458 xlog_recover_new_tid(
1459         xlog_recover_t          **q,
1460         xlog_tid_t              tid,
1461         xfs_lsn_t               lsn)
1462 {
1463         xlog_recover_t          *trans;
1464
1465         trans = kmem_zalloc(sizeof(xlog_recover_t), KM_SLEEP);
1466         trans->r_log_tid   = tid;
1467         trans->r_lsn       = lsn;
1468         xlog_recover_put_hashq(q, trans);
1469 }
1470
1471 STATIC int
1472 xlog_recover_unlink_tid(
1473         xlog_recover_t          **q,
1474         xlog_recover_t          *trans)
1475 {
1476         xlog_recover_t          *tp;
1477         int                     found = 0;
1478
1479         ASSERT(trans != NULL);
1480         if (trans == *q) {
1481                 *q = (*q)->r_next;
1482         } else {
1483                 tp = *q;
1484                 while (tp) {
1485                         if (tp->r_next == trans) {
1486                                 found = 1;
1487                                 break;
1488                         }
1489                         tp = tp->r_next;
1490                 }
1491                 if (!found) {
1492                         xlog_warn(
1493                              "XFS: xlog_recover_unlink_tid: trans not found");
1494                         ASSERT(0);
1495                         return XFS_ERROR(EIO);
1496                 }
1497                 tp->r_next = tp->r_next->r_next;
1498         }
1499         return 0;
1500 }
1501
1502 STATIC void
1503 xlog_recover_insert_item_backq(
1504         xlog_recover_item_t     **q,
1505         xlog_recover_item_t     *item)
1506 {
1507         if (*q == NULL) {
1508                 item->ri_prev = item->ri_next = item;
1509                 *q = item;
1510         } else {
1511                 item->ri_next           = *q;
1512                 item->ri_prev           = (*q)->ri_prev;
1513                 (*q)->ri_prev           = item;
1514                 item->ri_prev->ri_next  = item;
1515         }
1516 }
1517
1518 STATIC void
1519 xlog_recover_insert_item_frontq(
1520         xlog_recover_item_t     **q,
1521         xlog_recover_item_t     *item)
1522 {
1523         xlog_recover_insert_item_backq(q, item);
1524         *q = item;
1525 }
1526
1527 STATIC int
1528 xlog_recover_reorder_trans(
1529         xlog_recover_t          *trans)
1530 {
1531         xlog_recover_item_t     *first_item, *itemq, *itemq_next;
1532         xfs_buf_log_format_t    *buf_f;
1533         ushort                  flags = 0;
1534
1535         first_item = itemq = trans->r_itemq;
1536         trans->r_itemq = NULL;
1537         do {
1538                 itemq_next = itemq->ri_next;
1539                 buf_f = (xfs_buf_log_format_t *)itemq->ri_buf[0].i_addr;
1540
1541                 switch (ITEM_TYPE(itemq)) {
1542                 case XFS_LI_BUF:
1543                         flags = buf_f->blf_flags;
1544                         if (!(flags & XFS_BLI_CANCEL)) {
1545                                 xlog_recover_insert_item_frontq(&trans->r_itemq,
1546                                                                 itemq);
1547                                 break;
1548                         }
1549                 case XFS_LI_INODE:
1550                 case XFS_LI_DQUOT:
1551                 case XFS_LI_QUOTAOFF:
1552                 case XFS_LI_EFD:
1553                 case XFS_LI_EFI:
1554                         xlog_recover_insert_item_backq(&trans->r_itemq, itemq);
1555                         break;
1556                 default:
1557                         xlog_warn(
1558         "XFS: xlog_recover_reorder_trans: unrecognized type of log operation");
1559                         ASSERT(0);
1560                         return XFS_ERROR(EIO);
1561                 }
1562                 itemq = itemq_next;
1563         } while (first_item != itemq);
1564         return 0;
1565 }
1566
1567 /*
1568  * Build up the table of buf cancel records so that we don't replay
1569  * cancelled data in the second pass.  For buffer records that are
1570  * not cancel records, there is nothing to do here so we just return.
1571  *
1572  * If we get a cancel record which is already in the table, this indicates
1573  * that the buffer was cancelled multiple times.  In order to ensure
1574  * that during pass 2 we keep the record in the table until we reach its
1575  * last occurrence in the log, we keep a reference count in the cancel
1576  * record in the table to tell us how many times we expect to see this
1577  * record during the second pass.
1578  */
1579 STATIC void
1580 xlog_recover_do_buffer_pass1(
1581         xlog_t                  *log,
1582         xfs_buf_log_format_t    *buf_f)
1583 {
1584         xfs_buf_cancel_t        *bcp;
1585         xfs_buf_cancel_t        *nextp;
1586         xfs_buf_cancel_t        *prevp;
1587         xfs_buf_cancel_t        **bucket;
1588         xfs_daddr_t             blkno = 0;
1589         uint                    len = 0;
1590         ushort                  flags = 0;
1591
1592         switch (buf_f->blf_type) {
1593         case XFS_LI_BUF:
1594                 blkno = buf_f->blf_blkno;
1595                 len = buf_f->blf_len;
1596                 flags = buf_f->blf_flags;
1597                 break;
1598         }
1599
1600         /*
1601          * If this isn't a cancel buffer item, then just return.
1602          */
1603         if (!(flags & XFS_BLI_CANCEL))
1604                 return;
1605
1606         /*
1607          * Insert an xfs_buf_cancel record into the hash table of
1608          * them.  If there is already an identical record, bump
1609          * its reference count.
1610          */
1611         bucket = &log->l_buf_cancel_table[(__uint64_t)blkno %
1612                                           XLOG_BC_TABLE_SIZE];
1613         /*
1614          * If the hash bucket is empty then just insert a new record into
1615          * the bucket.
1616          */
1617         if (*bucket == NULL) {
1618                 bcp = (xfs_buf_cancel_t *)kmem_alloc(sizeof(xfs_buf_cancel_t),
1619                                                      KM_SLEEP);
1620                 bcp->bc_blkno = blkno;
1621                 bcp->bc_len = len;
1622                 bcp->bc_refcount = 1;
1623                 bcp->bc_next = NULL;
1624                 *bucket = bcp;
1625                 return;
1626         }
1627
1628         /*
1629          * The hash bucket is not empty, so search for duplicates of our
1630          * record.  If we find one them just bump its refcount.  If not
1631          * then add us at the end of the list.
1632          */
1633         prevp = NULL;
1634         nextp = *bucket;
1635         while (nextp != NULL) {
1636                 if (nextp->bc_blkno == blkno && nextp->bc_len == len) {
1637                         nextp->bc_refcount++;
1638                         return;
1639                 }
1640                 prevp = nextp;
1641                 nextp = nextp->bc_next;
1642         }
1643         ASSERT(prevp != NULL);
1644         bcp = (xfs_buf_cancel_t *)kmem_alloc(sizeof(xfs_buf_cancel_t),
1645                                              KM_SLEEP);
1646         bcp->bc_blkno = blkno;
1647         bcp->bc_len = len;
1648         bcp->bc_refcount = 1;
1649         bcp->bc_next = NULL;
1650         prevp->bc_next = bcp;
1651 }
1652
1653 /*
1654  * Check to see whether the buffer being recovered has a corresponding
1655  * entry in the buffer cancel record table.  If it does then return 1
1656  * so that it will be cancelled, otherwise return 0.  If the buffer is
1657  * actually a buffer cancel item (XFS_BLI_CANCEL is set), then decrement
1658  * the refcount on the entry in the table and remove it from the table
1659  * if this is the last reference.
1660  *
1661  * We remove the cancel record from the table when we encounter its
1662  * last occurrence in the log so that if the same buffer is re-used
1663  * again after its last cancellation we actually replay the changes
1664  * made at that point.
1665  */
1666 STATIC int
1667 xlog_check_buffer_cancelled(
1668         xlog_t                  *log,
1669         xfs_daddr_t             blkno,
1670         uint                    len,
1671         ushort                  flags)
1672 {
1673         xfs_buf_cancel_t        *bcp;
1674         xfs_buf_cancel_t        *prevp;
1675         xfs_buf_cancel_t        **bucket;
1676
1677         if (log->l_buf_cancel_table == NULL) {
1678                 /*
1679                  * There is nothing in the table built in pass one,
1680                  * so this buffer must not be cancelled.
1681                  */
1682                 ASSERT(!(flags & XFS_BLI_CANCEL));
1683                 return 0;
1684         }
1685
1686         bucket = &log->l_buf_cancel_table[(__uint64_t)blkno %
1687                                           XLOG_BC_TABLE_SIZE];
1688         bcp = *bucket;
1689         if (bcp == NULL) {
1690                 /*
1691                  * There is no corresponding entry in the table built
1692                  * in pass one, so this buffer has not been cancelled.
1693                  */
1694                 ASSERT(!(flags & XFS_BLI_CANCEL));
1695                 return 0;
1696         }
1697
1698         /*
1699          * Search for an entry in the buffer cancel table that
1700          * matches our buffer.
1701          */
1702         prevp = NULL;
1703         while (bcp != NULL) {
1704                 if (bcp->bc_blkno == blkno && bcp->bc_len == len) {
1705                         /*
1706                          * We've go a match, so return 1 so that the
1707                          * recovery of this buffer is cancelled.
1708                          * If this buffer is actually a buffer cancel
1709                          * log item, then decrement the refcount on the
1710                          * one in the table and remove it if this is the
1711                          * last reference.
1712                          */
1713                         if (flags & XFS_BLI_CANCEL) {
1714                                 bcp->bc_refcount--;
1715                                 if (bcp->bc_refcount == 0) {
1716                                         if (prevp == NULL) {
1717                                                 *bucket = bcp->bc_next;
1718                                         } else {
1719                                                 prevp->bc_next = bcp->bc_next;
1720                                         }
1721                                         kmem_free(bcp);
1722                                 }
1723                         }
1724                         return 1;
1725                 }
1726                 prevp = bcp;
1727                 bcp = bcp->bc_next;
1728         }
1729         /*
1730          * We didn't find a corresponding entry in the table, so
1731          * return 0 so that the buffer is NOT cancelled.
1732          */
1733         ASSERT(!(flags & XFS_BLI_CANCEL));
1734         return 0;
1735 }
1736
1737 STATIC int
1738 xlog_recover_do_buffer_pass2(
1739         xlog_t                  *log,
1740         xfs_buf_log_format_t    *buf_f)
1741 {
1742         xfs_daddr_t             blkno = 0;
1743         ushort                  flags = 0;
1744         uint                    len = 0;
1745
1746         switch (buf_f->blf_type) {
1747         case XFS_LI_BUF:
1748                 blkno = buf_f->blf_blkno;
1749                 flags = buf_f->blf_flags;
1750                 len = buf_f->blf_len;
1751                 break;
1752         }
1753
1754         return xlog_check_buffer_cancelled(log, blkno, len, flags);
1755 }
1756
1757 /*
1758  * Perform recovery for a buffer full of inodes.  In these buffers,
1759  * the only data which should be recovered is that which corresponds
1760  * to the di_next_unlinked pointers in the on disk inode structures.
1761  * The rest of the data for the inodes is always logged through the
1762  * inodes themselves rather than the inode buffer and is recovered
1763  * in xlog_recover_do_inode_trans().
1764  *
1765  * The only time when buffers full of inodes are fully recovered is
1766  * when the buffer is full of newly allocated inodes.  In this case
1767  * the buffer will not be marked as an inode buffer and so will be
1768  * sent to xlog_recover_do_reg_buffer() below during recovery.
1769  */
1770 STATIC int
1771 xlog_recover_do_inode_buffer(
1772         xfs_mount_t             *mp,
1773         xlog_recover_item_t     *item,
1774         xfs_buf_t               *bp,
1775         xfs_buf_log_format_t    *buf_f)
1776 {
1777         int                     i;
1778         int                     item_index;
1779         int                     bit;
1780         int                     nbits;
1781         int                     reg_buf_offset;
1782         int                     reg_buf_bytes;
1783         int                     next_unlinked_offset;
1784         int                     inodes_per_buf;
1785         xfs_agino_t             *logged_nextp;
1786         xfs_agino_t             *buffer_nextp;
1787         unsigned int            *data_map = NULL;
1788         unsigned int            map_size = 0;
1789
1790         switch (buf_f->blf_type) {
1791         case XFS_LI_BUF:
1792                 data_map = buf_f->blf_data_map;
1793                 map_size = buf_f->blf_map_size;
1794                 break;
1795         }
1796         /*
1797          * Set the variables corresponding to the current region to
1798          * 0 so that we'll initialize them on the first pass through
1799          * the loop.
1800          */
1801         reg_buf_offset = 0;
1802         reg_buf_bytes = 0;
1803         bit = 0;
1804         nbits = 0;
1805         item_index = 0;
1806         inodes_per_buf = XFS_BUF_COUNT(bp) >> mp->m_sb.sb_inodelog;
1807         for (i = 0; i < inodes_per_buf; i++) {
1808                 next_unlinked_offset = (i * mp->m_sb.sb_inodesize) +
1809                         offsetof(xfs_dinode_t, di_next_unlinked);
1810
1811                 while (next_unlinked_offset >=
1812                        (reg_buf_offset + reg_buf_bytes)) {
1813                         /*
1814                          * The next di_next_unlinked field is beyond
1815                          * the current logged region.  Find the next
1816                          * logged region that contains or is beyond
1817                          * the current di_next_unlinked field.
1818                          */
1819                         bit += nbits;
1820                         bit = xfs_next_bit(data_map, map_size, bit);
1821
1822                         /*
1823                          * If there are no more logged regions in the
1824                          * buffer, then we're done.
1825                          */
1826                         if (bit == -1) {
1827                                 return 0;
1828                         }
1829
1830                         nbits = xfs_contig_bits(data_map, map_size,
1831                                                          bit);
1832                         ASSERT(nbits > 0);
1833                         reg_buf_offset = bit << XFS_BLI_SHIFT;
1834                         reg_buf_bytes = nbits << XFS_BLI_SHIFT;
1835                         item_index++;
1836                 }
1837
1838                 /*
1839                  * If the current logged region starts after the current
1840                  * di_next_unlinked field, then move on to the next
1841                  * di_next_unlinked field.
1842                  */
1843                 if (next_unlinked_offset < reg_buf_offset) {
1844                         continue;
1845                 }
1846
1847                 ASSERT(item->ri_buf[item_index].i_addr != NULL);
1848                 ASSERT((item->ri_buf[item_index].i_len % XFS_BLI_CHUNK) == 0);
1849                 ASSERT((reg_buf_offset + reg_buf_bytes) <= XFS_BUF_COUNT(bp));
1850
1851                 /*
1852                  * The current logged region contains a copy of the
1853                  * current di_next_unlinked field.  Extract its value
1854                  * and copy it to the buffer copy.
1855                  */
1856                 logged_nextp = (xfs_agino_t *)
1857                                ((char *)(item->ri_buf[item_index].i_addr) +
1858                                 (next_unlinked_offset - reg_buf_offset));
1859                 if (unlikely(*logged_nextp == 0)) {
1860                         xfs_fs_cmn_err(CE_ALERT, mp,
1861                                 "bad inode buffer log record (ptr = 0x%p, bp = 0x%p).  XFS trying to replay bad (0) inode di_next_unlinked field",
1862                                 item, bp);
1863                         XFS_ERROR_REPORT("xlog_recover_do_inode_buf",
1864                                          XFS_ERRLEVEL_LOW, mp);
1865                         return XFS_ERROR(EFSCORRUPTED);
1866                 }
1867
1868                 buffer_nextp = (xfs_agino_t *)xfs_buf_offset(bp,
1869                                               next_unlinked_offset);
1870                 *buffer_nextp = *logged_nextp;
1871         }
1872
1873         return 0;
1874 }
1875
1876 /*
1877  * Perform a 'normal' buffer recovery.  Each logged region of the
1878  * buffer should be copied over the corresponding region in the
1879  * given buffer.  The bitmap in the buf log format structure indicates
1880  * where to place the logged data.
1881  */
1882 /*ARGSUSED*/
1883 STATIC void
1884 xlog_recover_do_reg_buffer(
1885         xlog_recover_item_t     *item,
1886         xfs_buf_t               *bp,
1887         xfs_buf_log_format_t    *buf_f)
1888 {
1889         int                     i;
1890         int                     bit;
1891         int                     nbits;
1892         unsigned int            *data_map = NULL;
1893         unsigned int            map_size = 0;
1894         int                     error;
1895
1896         switch (buf_f->blf_type) {
1897         case XFS_LI_BUF:
1898                 data_map = buf_f->blf_data_map;
1899                 map_size = buf_f->blf_map_size;
1900                 break;
1901         }
1902         bit = 0;
1903         i = 1;  /* 0 is the buf format structure */
1904         while (1) {
1905                 bit = xfs_next_bit(data_map, map_size, bit);
1906                 if (bit == -1)
1907                         break;
1908                 nbits = xfs_contig_bits(data_map, map_size, bit);
1909                 ASSERT(nbits > 0);
1910                 ASSERT(item->ri_buf[i].i_addr != NULL);
1911                 ASSERT(item->ri_buf[i].i_len % XFS_BLI_CHUNK == 0);
1912                 ASSERT(XFS_BUF_COUNT(bp) >=
1913                        ((uint)bit << XFS_BLI_SHIFT)+(nbits<<XFS_BLI_SHIFT));
1914
1915                 /*
1916                  * Do a sanity check if this is a dquot buffer. Just checking
1917                  * the first dquot in the buffer should do. XXXThis is
1918                  * probably a good thing to do for other buf types also.
1919                  */
1920                 error = 0;
1921                 if (buf_f->blf_flags &
1922                    (XFS_BLI_UDQUOT_BUF|XFS_BLI_PDQUOT_BUF|XFS_BLI_GDQUOT_BUF)) {
1923                         error = xfs_qm_dqcheck((xfs_disk_dquot_t *)
1924                                                item->ri_buf[i].i_addr,
1925                                                -1, 0, XFS_QMOPT_DOWARN,
1926                                                "dquot_buf_recover");
1927                 }
1928                 if (!error)
1929                         memcpy(xfs_buf_offset(bp,
1930                                 (uint)bit << XFS_BLI_SHIFT),    /* dest */
1931                                 item->ri_buf[i].i_addr,         /* source */
1932                                 nbits<<XFS_BLI_SHIFT);          /* length */
1933                 i++;
1934                 bit += nbits;
1935         }
1936
1937         /* Shouldn't be any more regions */
1938         ASSERT(i == item->ri_total);
1939 }
1940
1941 /*
1942  * Do some primitive error checking on ondisk dquot data structures.
1943  */
1944 int
1945 xfs_qm_dqcheck(
1946         xfs_disk_dquot_t *ddq,
1947         xfs_dqid_t       id,
1948         uint             type,    /* used only when IO_dorepair is true */
1949         uint             flags,
1950         char             *str)
1951 {
1952         xfs_dqblk_t      *d = (xfs_dqblk_t *)ddq;
1953         int             errs = 0;
1954
1955         /*
1956          * We can encounter an uninitialized dquot buffer for 2 reasons:
1957          * 1. If we crash while deleting the quotainode(s), and those blks got
1958          *    used for user data. This is because we take the path of regular
1959          *    file deletion; however, the size field of quotainodes is never
1960          *    updated, so all the tricks that we play in itruncate_finish
1961          *    don't quite matter.
1962          *
1963          * 2. We don't play the quota buffers when there's a quotaoff logitem.
1964          *    But the allocation will be replayed so we'll end up with an
1965          *    uninitialized quota block.
1966          *
1967          * This is all fine; things are still consistent, and we haven't lost
1968          * any quota information. Just don't complain about bad dquot blks.
1969          */
1970         if (be16_to_cpu(ddq->d_magic) != XFS_DQUOT_MAGIC) {
1971                 if (flags & XFS_QMOPT_DOWARN)
1972                         cmn_err(CE_ALERT,
1973                         "%s : XFS dquot ID 0x%x, magic 0x%x != 0x%x",
1974                         str, id, be16_to_cpu(ddq->d_magic), XFS_DQUOT_MAGIC);
1975                 errs++;
1976         }
1977         if (ddq->d_version != XFS_DQUOT_VERSION) {
1978                 if (flags & XFS_QMOPT_DOWARN)
1979                         cmn_err(CE_ALERT,
1980                         "%s : XFS dquot ID 0x%x, version 0x%x != 0x%x",
1981                         str, id, ddq->d_version, XFS_DQUOT_VERSION);
1982                 errs++;
1983         }
1984
1985         if (ddq->d_flags != XFS_DQ_USER &&
1986             ddq->d_flags != XFS_DQ_PROJ &&
1987             ddq->d_flags != XFS_DQ_GROUP) {
1988                 if (flags & XFS_QMOPT_DOWARN)
1989                         cmn_err(CE_ALERT,
1990                         "%s : XFS dquot ID 0x%x, unknown flags 0x%x",
1991                         str, id, ddq->d_flags);
1992                 errs++;
1993         }
1994
1995         if (id != -1 && id != be32_to_cpu(ddq->d_id)) {
1996                 if (flags & XFS_QMOPT_DOWARN)
1997                         cmn_err(CE_ALERT,
1998                         "%s : ondisk-dquot 0x%p, ID mismatch: "
1999                         "0x%x expected, found id 0x%x",
2000                         str, ddq, id, be32_to_cpu(ddq->d_id));
2001                 errs++;
2002         }
2003
2004         if (!errs && ddq->d_id) {
2005                 if (ddq->d_blk_softlimit &&
2006                     be64_to_cpu(ddq->d_bcount) >=
2007                                 be64_to_cpu(ddq->d_blk_softlimit)) {
2008                         if (!ddq->d_btimer) {
2009                                 if (flags & XFS_QMOPT_DOWARN)
2010                                         cmn_err(CE_ALERT,
2011                                         "%s : Dquot ID 0x%x (0x%p) "
2012                                         "BLK TIMER NOT STARTED",
2013                                         str, (int)be32_to_cpu(ddq->d_id), ddq);
2014                                 errs++;
2015                         }
2016                 }
2017                 if (ddq->d_ino_softlimit &&
2018                     be64_to_cpu(ddq->d_icount) >=
2019                                 be64_to_cpu(ddq->d_ino_softlimit)) {
2020                         if (!ddq->d_itimer) {
2021                                 if (flags & XFS_QMOPT_DOWARN)
2022                                         cmn_err(CE_ALERT,
2023                                         "%s : Dquot ID 0x%x (0x%p) "
2024                                         "INODE TIMER NOT STARTED",
2025                                         str, (int)be32_to_cpu(ddq->d_id), ddq);
2026                                 errs++;
2027                         }
2028                 }
2029                 if (ddq->d_rtb_softlimit &&
2030                     be64_to_cpu(ddq->d_rtbcount) >=
2031                                 be64_to_cpu(ddq->d_rtb_softlimit)) {
2032                         if (!ddq->d_rtbtimer) {
2033                                 if (flags & XFS_QMOPT_DOWARN)
2034                                         cmn_err(CE_ALERT,
2035                                         "%s : Dquot ID 0x%x (0x%p) "
2036                                         "RTBLK TIMER NOT STARTED",
2037                                         str, (int)be32_to_cpu(ddq->d_id), ddq);
2038                                 errs++;
2039                         }
2040                 }
2041         }
2042
2043         if (!errs || !(flags & XFS_QMOPT_DQREPAIR))
2044                 return errs;
2045
2046         if (flags & XFS_QMOPT_DOWARN)
2047                 cmn_err(CE_NOTE, "Re-initializing dquot ID 0x%x", id);
2048
2049         /*
2050          * Typically, a repair is only requested by quotacheck.
2051          */
2052         ASSERT(id != -1);
2053         ASSERT(flags & XFS_QMOPT_DQREPAIR);
2054         memset(d, 0, sizeof(xfs_dqblk_t));
2055
2056         d->dd_diskdq.d_magic = cpu_to_be16(XFS_DQUOT_MAGIC);
2057         d->dd_diskdq.d_version = XFS_DQUOT_VERSION;
2058         d->dd_diskdq.d_flags = type;
2059         d->dd_diskdq.d_id = cpu_to_be32(id);
2060
2061         return errs;
2062 }
2063
2064 /*
2065  * Perform a dquot buffer recovery.
2066  * Simple algorithm: if we have found a QUOTAOFF logitem of the same type
2067  * (ie. USR or GRP), then just toss this buffer away; don't recover it.
2068  * Else, treat it as a regular buffer and do recovery.
2069  */
2070 STATIC void
2071 xlog_recover_do_dquot_buffer(
2072         xfs_mount_t             *mp,
2073         xlog_t                  *log,
2074         xlog_recover_item_t     *item,
2075         xfs_buf_t               *bp,
2076         xfs_buf_log_format_t    *buf_f)
2077 {
2078         uint                    type;
2079
2080         /*
2081          * Filesystems are required to send in quota flags at mount time.
2082          */
2083         if (mp->m_qflags == 0) {
2084                 return;
2085         }
2086
2087         type = 0;
2088         if (buf_f->blf_flags & XFS_BLI_UDQUOT_BUF)
2089                 type |= XFS_DQ_USER;
2090         if (buf_f->blf_flags & XFS_BLI_PDQUOT_BUF)
2091                 type |= XFS_DQ_PROJ;
2092         if (buf_f->blf_flags & XFS_BLI_GDQUOT_BUF)
2093                 type |= XFS_DQ_GROUP;
2094         /*
2095          * This type of quotas was turned off, so ignore this buffer
2096          */
2097         if (log->l_quotaoffs_flag & type)
2098                 return;
2099
2100         xlog_recover_do_reg_buffer(item, bp, buf_f);
2101 }
2102
2103 /*
2104  * This routine replays a modification made to a buffer at runtime.
2105  * There are actually two types of buffer, regular and inode, which
2106  * are handled differently.  Inode buffers are handled differently
2107  * in that we only recover a specific set of data from them, namely
2108  * the inode di_next_unlinked fields.  This is because all other inode
2109  * data is actually logged via inode records and any data we replay
2110  * here which overlaps that may be stale.
2111  *
2112  * When meta-data buffers are freed at run time we log a buffer item
2113  * with the XFS_BLI_CANCEL bit set to indicate that previous copies
2114  * of the buffer in the log should not be replayed at recovery time.
2115  * This is so that if the blocks covered by the buffer are reused for
2116  * file data before we crash we don't end up replaying old, freed
2117  * meta-data into a user's file.
2118  *
2119  * To handle the cancellation of buffer log items, we make two passes
2120  * over the log during recovery.  During the first we build a table of
2121  * those buffers which have been cancelled, and during the second we
2122  * only replay those buffers which do not have corresponding cancel
2123  * records in the table.  See xlog_recover_do_buffer_pass[1,2] above
2124  * for more details on the implementation of the table of cancel records.
2125  */
2126 STATIC int
2127 xlog_recover_do_buffer_trans(
2128         xlog_t                  *log,
2129         xlog_recover_item_t     *item,
2130         int                     pass)
2131 {
2132         xfs_buf_log_format_t    *buf_f;
2133         xfs_mount_t             *mp;
2134         xfs_buf_t               *bp;
2135         int                     error;
2136         int                     cancel;
2137         xfs_daddr_t             blkno;
2138         int                     len;
2139         ushort                  flags;
2140
2141         buf_f = (xfs_buf_log_format_t *)item->ri_buf[0].i_addr;
2142
2143         if (pass == XLOG_RECOVER_PASS1) {
2144                 /*
2145                  * In this pass we're only looking for buf items
2146                  * with the XFS_BLI_CANCEL bit set.
2147                  */
2148                 xlog_recover_do_buffer_pass1(log, buf_f);
2149                 return 0;
2150         } else {
2151                 /*
2152                  * In this pass we want to recover all the buffers
2153                  * which have not been cancelled and are not
2154                  * cancellation buffers themselves.  The routine
2155                  * we call here will tell us whether or not to
2156                  * continue with the replay of this buffer.
2157                  */
2158                 cancel = xlog_recover_do_buffer_pass2(log, buf_f);
2159                 if (cancel) {
2160                         return 0;
2161                 }
2162         }
2163         switch (buf_f->blf_type) {
2164         case XFS_LI_BUF:
2165                 blkno = buf_f->blf_blkno;
2166                 len = buf_f->blf_len;
2167                 flags = buf_f->blf_flags;
2168                 break;
2169         default:
2170                 xfs_fs_cmn_err(CE_ALERT, log->l_mp,
2171                         "xfs_log_recover: unknown buffer type 0x%x, logdev %s",
2172                         buf_f->blf_type, log->l_mp->m_logname ?
2173                         log->l_mp->m_logname : "internal");
2174                 XFS_ERROR_REPORT("xlog_recover_do_buffer_trans",
2175                                  XFS_ERRLEVEL_LOW, log->l_mp);
2176                 return XFS_ERROR(EFSCORRUPTED);
2177         }
2178
2179         mp = log->l_mp;
2180         if (flags & XFS_BLI_INODE_BUF) {
2181                 bp = xfs_buf_read_flags(mp->m_ddev_targp, blkno, len,
2182                                                                 XFS_BUF_LOCK);
2183         } else {
2184                 bp = xfs_buf_read(mp->m_ddev_targp, blkno, len, 0);
2185         }
2186         if (XFS_BUF_ISERROR(bp)) {
2187                 xfs_ioerror_alert("xlog_recover_do..(read#1)", log->l_mp,
2188                                   bp, blkno);
2189                 error = XFS_BUF_GETERROR(bp);
2190                 xfs_buf_relse(bp);
2191                 return error;
2192         }
2193
2194         error = 0;
2195         if (flags & XFS_BLI_INODE_BUF) {
2196                 error = xlog_recover_do_inode_buffer(mp, item, bp, buf_f);
2197         } else if (flags &
2198                   (XFS_BLI_UDQUOT_BUF|XFS_BLI_PDQUOT_BUF|XFS_BLI_GDQUOT_BUF)) {
2199                 xlog_recover_do_dquot_buffer(mp, log, item, bp, buf_f);
2200         } else {
2201                 xlog_recover_do_reg_buffer(item, bp, buf_f);
2202         }
2203         if (error)
2204                 return XFS_ERROR(error);
2205
2206         /*
2207          * Perform delayed write on the buffer.  Asynchronous writes will be
2208          * slower when taking into account all the buffers to be flushed.
2209          *
2210          * Also make sure that only inode buffers with good sizes stay in
2211          * the buffer cache.  The kernel moves inodes in buffers of 1 block
2212          * or XFS_INODE_CLUSTER_SIZE bytes, whichever is bigger.  The inode
2213          * buffers in the log can be a different size if the log was generated
2214          * by an older kernel using unclustered inode buffers or a newer kernel
2215          * running with a different inode cluster size.  Regardless, if the
2216          * the inode buffer size isn't MAX(blocksize, XFS_INODE_CLUSTER_SIZE)
2217          * for *our* value of XFS_INODE_CLUSTER_SIZE, then we need to keep
2218          * the buffer out of the buffer cache so that the buffer won't
2219          * overlap with future reads of those inodes.
2220          */
2221         if (XFS_DINODE_MAGIC ==
2222             be16_to_cpu(*((__be16 *)xfs_buf_offset(bp, 0))) &&
2223             (XFS_BUF_COUNT(bp) != MAX(log->l_mp->m_sb.sb_blocksize,
2224                         (__uint32_t)XFS_INODE_CLUSTER_SIZE(log->l_mp)))) {
2225                 XFS_BUF_STALE(bp);
2226                 error = xfs_bwrite(mp, bp);
2227         } else {
2228                 ASSERT(XFS_BUF_FSPRIVATE(bp, void *) == NULL ||
2229                        XFS_BUF_FSPRIVATE(bp, xfs_mount_t *) == mp);
2230                 XFS_BUF_SET_FSPRIVATE(bp, mp);
2231                 XFS_BUF_SET_IODONE_FUNC(bp, xlog_recover_iodone);
2232                 xfs_bdwrite(mp, bp);
2233         }
2234
2235         return (error);
2236 }
2237
2238 STATIC int
2239 xlog_recover_do_inode_trans(
2240         xlog_t                  *log,
2241         xlog_recover_item_t     *item,
2242         int                     pass)
2243 {
2244         xfs_inode_log_format_t  *in_f;
2245         xfs_mount_t             *mp;
2246         xfs_buf_t               *bp;
2247         xfs_dinode_t            *dip;
2248         xfs_ino_t               ino;
2249         int                     len;
2250         xfs_caddr_t             src;
2251         xfs_caddr_t             dest;
2252         int                     error;
2253         int                     attr_index;
2254         uint                    fields;
2255         xfs_icdinode_t          *dicp;
2256         int                     need_free = 0;
2257
2258         if (pass == XLOG_RECOVER_PASS1) {
2259                 return 0;
2260         }
2261
2262         if (item->ri_buf[0].i_len == sizeof(xfs_inode_log_format_t)) {
2263                 in_f = (xfs_inode_log_format_t *)item->ri_buf[0].i_addr;
2264         } else {
2265                 in_f = (xfs_inode_log_format_t *)kmem_alloc(
2266                         sizeof(xfs_inode_log_format_t), KM_SLEEP);
2267                 need_free = 1;
2268                 error = xfs_inode_item_format_convert(&item->ri_buf[0], in_f);
2269                 if (error)
2270                         goto error;
2271         }
2272         ino = in_f->ilf_ino;
2273         mp = log->l_mp;
2274
2275         /*
2276          * Inode buffers can be freed, look out for it,
2277          * and do not replay the inode.
2278          */
2279         if (xlog_check_buffer_cancelled(log, in_f->ilf_blkno,
2280                                         in_f->ilf_len, 0)) {
2281                 error = 0;
2282                 goto error;
2283         }
2284
2285         bp = xfs_buf_read_flags(mp->m_ddev_targp, in_f->ilf_blkno,
2286                                 in_f->ilf_len, XFS_BUF_LOCK);
2287         if (XFS_BUF_ISERROR(bp)) {
2288                 xfs_ioerror_alert("xlog_recover_do..(read#2)", mp,
2289                                   bp, in_f->ilf_blkno);
2290                 error = XFS_BUF_GETERROR(bp);
2291                 xfs_buf_relse(bp);
2292                 goto error;
2293         }
2294         error = 0;
2295         ASSERT(in_f->ilf_fields & XFS_ILOG_CORE);
2296         dip = (xfs_dinode_t *)xfs_buf_offset(bp, in_f->ilf_boffset);
2297
2298         /*
2299          * Make sure the place we're flushing out to really looks
2300          * like an inode!
2301          */
2302         if (unlikely(be16_to_cpu(dip->di_magic) != XFS_DINODE_MAGIC)) {
2303                 xfs_buf_relse(bp);
2304                 xfs_fs_cmn_err(CE_ALERT, mp,
2305                         "xfs_inode_recover: Bad inode magic number, dino ptr = 0x%p, dino bp = 0x%p, ino = %Ld",
2306                         dip, bp, ino);
2307                 XFS_ERROR_REPORT("xlog_recover_do_inode_trans(1)",
2308                                  XFS_ERRLEVEL_LOW, mp);
2309                 error = EFSCORRUPTED;
2310                 goto error;
2311         }
2312         dicp = (xfs_icdinode_t *)(item->ri_buf[1].i_addr);
2313         if (unlikely(dicp->di_magic != XFS_DINODE_MAGIC)) {
2314                 xfs_buf_relse(bp);
2315                 xfs_fs_cmn_err(CE_ALERT, mp,
2316                         "xfs_inode_recover: Bad inode log record, rec ptr 0x%p, ino %Ld",
2317                         item, ino);
2318                 XFS_ERROR_REPORT("xlog_recover_do_inode_trans(2)",
2319                                  XFS_ERRLEVEL_LOW, mp);
2320                 error = EFSCORRUPTED;
2321                 goto error;
2322         }
2323
2324         /* Skip replay when the on disk inode is newer than the log one */
2325         if (dicp->di_flushiter < be16_to_cpu(dip->di_flushiter)) {
2326                 /*
2327                  * Deal with the wrap case, DI_MAX_FLUSH is less
2328                  * than smaller numbers
2329                  */
2330                 if (be16_to_cpu(dip->di_flushiter) == DI_MAX_FLUSH &&
2331                     dicp->di_flushiter < (DI_MAX_FLUSH >> 1)) {
2332                         /* do nothing */
2333                 } else {
2334                         xfs_buf_relse(bp);
2335                         error = 0;
2336                         goto error;
2337                 }
2338         }
2339         /* Take the opportunity to reset the flush iteration count */
2340         dicp->di_flushiter = 0;
2341
2342         if (unlikely((dicp->di_mode & S_IFMT) == S_IFREG)) {
2343                 if ((dicp->di_format != XFS_DINODE_FMT_EXTENTS) &&
2344                     (dicp->di_format != XFS_DINODE_FMT_BTREE)) {
2345                         XFS_CORRUPTION_ERROR("xlog_recover_do_inode_trans(3)",
2346                                          XFS_ERRLEVEL_LOW, mp, dicp);
2347                         xfs_buf_relse(bp);
2348                         xfs_fs_cmn_err(CE_ALERT, mp,
2349                                 "xfs_inode_recover: Bad regular inode log record, rec ptr 0x%p, ino ptr = 0x%p, ino bp = 0x%p, ino %Ld",
2350                                 item, dip, bp, ino);
2351                         error = EFSCORRUPTED;
2352                         goto error;
2353                 }
2354         } else if (unlikely((dicp->di_mode & S_IFMT) == S_IFDIR)) {
2355                 if ((dicp->di_format != XFS_DINODE_FMT_EXTENTS) &&
2356                     (dicp->di_format != XFS_DINODE_FMT_BTREE) &&
2357                     (dicp->di_format != XFS_DINODE_FMT_LOCAL)) {
2358                         XFS_CORRUPTION_ERROR("xlog_recover_do_inode_trans(4)",
2359                                              XFS_ERRLEVEL_LOW, mp, dicp);
2360                         xfs_buf_relse(bp);
2361                         xfs_fs_cmn_err(CE_ALERT, mp,
2362                                 "xfs_inode_recover: Bad dir inode log record, rec ptr 0x%p, ino ptr = 0x%p, ino bp = 0x%p, ino %Ld",
2363                                 item, dip, bp, ino);
2364                         error = EFSCORRUPTED;
2365                         goto error;
2366                 }
2367         }
2368         if (unlikely(dicp->di_nextents + dicp->di_anextents > dicp->di_nblocks)){
2369                 XFS_CORRUPTION_ERROR("xlog_recover_do_inode_trans(5)",
2370                                      XFS_ERRLEVEL_LOW, mp, dicp);
2371                 xfs_buf_relse(bp);
2372                 xfs_fs_cmn_err(CE_ALERT, mp,
2373                         "xfs_inode_recover: Bad inode log record, rec ptr 0x%p, dino ptr 0x%p, dino bp 0x%p, ino %Ld, total extents = %d, nblocks = %Ld",
2374                         item, dip, bp, ino,
2375                         dicp->di_nextents + dicp->di_anextents,
2376                         dicp->di_nblocks);
2377                 error = EFSCORRUPTED;
2378                 goto error;
2379         }
2380         if (unlikely(dicp->di_forkoff > mp->m_sb.sb_inodesize)) {
2381                 XFS_CORRUPTION_ERROR("xlog_recover_do_inode_trans(6)",
2382                                      XFS_ERRLEVEL_LOW, mp, dicp);
2383                 xfs_buf_relse(bp);
2384                 xfs_fs_cmn_err(CE_ALERT, mp,
2385                         "xfs_inode_recover: Bad inode log rec ptr 0x%p, dino ptr 0x%p, dino bp 0x%p, ino %Ld, forkoff 0x%x",
2386                         item, dip, bp, ino, dicp->di_forkoff);
2387                 error = EFSCORRUPTED;
2388                 goto error;
2389         }
2390         if (unlikely(item->ri_buf[1].i_len > sizeof(struct xfs_icdinode))) {
2391                 XFS_CORRUPTION_ERROR("xlog_recover_do_inode_trans(7)",
2392                                      XFS_ERRLEVEL_LOW, mp, dicp);
2393                 xfs_buf_relse(bp);
2394                 xfs_fs_cmn_err(CE_ALERT, mp,
2395                         "xfs_inode_recover: Bad inode log record length %d, rec ptr 0x%p",
2396                         item->ri_buf[1].i_len, item);
2397                 error = EFSCORRUPTED;
2398                 goto error;
2399         }
2400
2401         /* The core is in in-core format */
2402         xfs_dinode_to_disk(dip, (xfs_icdinode_t *)item->ri_buf[1].i_addr);
2403
2404         /* the rest is in on-disk format */
2405         if (item->ri_buf[1].i_len > sizeof(struct xfs_icdinode)) {
2406                 memcpy((xfs_caddr_t) dip + sizeof(struct xfs_icdinode),
2407                         item->ri_buf[1].i_addr + sizeof(struct xfs_icdinode),
2408                         item->ri_buf[1].i_len  - sizeof(struct xfs_icdinode));
2409         }
2410
2411         fields = in_f->ilf_fields;
2412         switch (fields & (XFS_ILOG_DEV | XFS_ILOG_UUID)) {
2413         case XFS_ILOG_DEV:
2414                 xfs_dinode_put_rdev(dip, in_f->ilf_u.ilfu_rdev);
2415                 break;
2416         case XFS_ILOG_UUID:
2417                 memcpy(XFS_DFORK_DPTR(dip),
2418                        &in_f->ilf_u.ilfu_uuid,
2419                        sizeof(uuid_t));
2420                 break;
2421         }
2422
2423         if (in_f->ilf_size == 2)
2424                 goto write_inode_buffer;
2425         len = item->ri_buf[2].i_len;
2426         src = item->ri_buf[2].i_addr;
2427         ASSERT(in_f->ilf_size <= 4);
2428         ASSERT((in_f->ilf_size == 3) || (fields & XFS_ILOG_AFORK));
2429         ASSERT(!(fields & XFS_ILOG_DFORK) ||
2430                (len == in_f->ilf_dsize));
2431
2432         switch (fields & XFS_ILOG_DFORK) {
2433         case XFS_ILOG_DDATA:
2434         case XFS_ILOG_DEXT:
2435                 memcpy(XFS_DFORK_DPTR(dip), src, len);
2436                 break;
2437
2438         case XFS_ILOG_DBROOT:
2439                 xfs_bmbt_to_bmdr(mp, (struct xfs_btree_block *)src, len,
2440                                  (xfs_bmdr_block_t *)XFS_DFORK_DPTR(dip),
2441                                  XFS_DFORK_DSIZE(dip, mp));
2442                 break;
2443
2444         default:
2445                 /*
2446                  * There are no data fork flags set.
2447                  */
2448                 ASSERT((fields & XFS_ILOG_DFORK) == 0);
2449                 break;
2450         }
2451
2452         /*
2453          * If we logged any attribute data, recover it.  There may or
2454          * may not have been any other non-core data logged in this
2455          * transaction.
2456          */
2457         if (in_f->ilf_fields & XFS_ILOG_AFORK) {
2458                 if (in_f->ilf_fields & XFS_ILOG_DFORK) {
2459                         attr_index = 3;
2460                 } else {
2461                         attr_index = 2;
2462                 }
2463                 len = item->ri_buf[attr_index].i_len;
2464                 src = item->ri_buf[attr_index].i_addr;
2465                 ASSERT(len == in_f->ilf_asize);
2466
2467                 switch (in_f->ilf_fields & XFS_ILOG_AFORK) {
2468                 case XFS_ILOG_ADATA:
2469                 case XFS_ILOG_AEXT:
2470                         dest = XFS_DFORK_APTR(dip);
2471                         ASSERT(len <= XFS_DFORK_ASIZE(dip, mp));
2472                         memcpy(dest, src, len);
2473                         break;
2474
2475                 case XFS_ILOG_ABROOT:
2476                         dest = XFS_DFORK_APTR(dip);
2477                         xfs_bmbt_to_bmdr(mp, (struct xfs_btree_block *)src,
2478                                          len, (xfs_bmdr_block_t*)dest,
2479                                          XFS_DFORK_ASIZE(dip, mp));
2480                         break;
2481
2482                 default:
2483                         xlog_warn("XFS: xlog_recover_do_inode_trans: Invalid flag");
2484                         ASSERT(0);
2485                         xfs_buf_relse(bp);
2486                         error = EIO;
2487                         goto error;
2488                 }
2489         }
2490
2491 write_inode_buffer:
2492         if (ITEM_TYPE(item) == XFS_LI_INODE) {
2493                 ASSERT(XFS_BUF_FSPRIVATE(bp, void *) == NULL ||
2494                        XFS_BUF_FSPRIVATE(bp, xfs_mount_t *) == mp);
2495                 XFS_BUF_SET_FSPRIVATE(bp, mp);
2496                 XFS_BUF_SET_IODONE_FUNC(bp, xlog_recover_iodone);
2497                 xfs_bdwrite(mp, bp);
2498         } else {
2499                 XFS_BUF_STALE(bp);
2500                 error = xfs_bwrite(mp, bp);
2501         }
2502
2503 error:
2504         if (need_free)
2505                 kmem_free(in_f);
2506         return XFS_ERROR(error);
2507 }
2508
2509 /*
2510  * Recover QUOTAOFF records. We simply make a note of it in the xlog_t
2511  * structure, so that we know not to do any dquot item or dquot buffer recovery,
2512  * of that type.
2513  */
2514 STATIC int
2515 xlog_recover_do_quotaoff_trans(
2516         xlog_t                  *log,
2517         xlog_recover_item_t     *item,
2518         int                     pass)
2519 {
2520         xfs_qoff_logformat_t    *qoff_f;
2521
2522         if (pass == XLOG_RECOVER_PASS2) {
2523                 return (0);
2524         }
2525
2526         qoff_f = (xfs_qoff_logformat_t *)item->ri_buf[0].i_addr;
2527         ASSERT(qoff_f);
2528
2529         /*
2530          * The logitem format's flag tells us if this was user quotaoff,
2531          * group/project quotaoff or both.
2532          */
2533         if (qoff_f->qf_flags & XFS_UQUOTA_ACCT)
2534                 log->l_quotaoffs_flag |= XFS_DQ_USER;
2535         if (qoff_f->qf_flags & XFS_PQUOTA_ACCT)
2536                 log->l_quotaoffs_flag |= XFS_DQ_PROJ;
2537         if (qoff_f->qf_flags & XFS_GQUOTA_ACCT)
2538                 log->l_quotaoffs_flag |= XFS_DQ_GROUP;
2539
2540         return (0);
2541 }
2542
2543 /*
2544  * Recover a dquot record
2545  */
2546 STATIC int
2547 xlog_recover_do_dquot_trans(
2548         xlog_t                  *log,
2549         xlog_recover_item_t     *item,
2550         int                     pass)
2551 {
2552         xfs_mount_t             *mp;
2553         xfs_buf_t               *bp;
2554         struct xfs_disk_dquot   *ddq, *recddq;
2555         int                     error;
2556         xfs_dq_logformat_t      *dq_f;
2557         uint                    type;
2558
2559         if (pass == XLOG_RECOVER_PASS1) {
2560                 return 0;
2561         }
2562         mp = log->l_mp;
2563
2564         /*
2565          * Filesystems are required to send in quota flags at mount time.
2566          */
2567         if (mp->m_qflags == 0)
2568                 return (0);
2569
2570         recddq = (xfs_disk_dquot_t *)item->ri_buf[1].i_addr;
2571         ASSERT(recddq);
2572         /*
2573          * This type of quotas was turned off, so ignore this record.
2574          */
2575         type = recddq->d_flags & (XFS_DQ_USER | XFS_DQ_PROJ | XFS_DQ_GROUP);
2576         ASSERT(type);
2577         if (log->l_quotaoffs_flag & type)
2578                 return (0);
2579
2580         /*
2581          * At this point we know that quota was _not_ turned off.
2582          * Since the mount flags are not indicating to us otherwise, this
2583          * must mean that quota is on, and the dquot needs to be replayed.
2584          * Remember that we may not have fully recovered the superblock yet,
2585          * so we can't do the usual trick of looking at the SB quota bits.
2586          *
2587          * The other possibility, of course, is that the quota subsystem was
2588          * removed since the last mount - ENOSYS.
2589          */
2590         dq_f = (xfs_dq_logformat_t *)item->ri_buf[0].i_addr;
2591         ASSERT(dq_f);
2592         if ((error = xfs_qm_dqcheck(recddq,
2593                            dq_f->qlf_id,
2594                            0, XFS_QMOPT_DOWARN,
2595                            "xlog_recover_do_dquot_trans (log copy)"))) {
2596                 return XFS_ERROR(EIO);
2597         }
2598         ASSERT(dq_f->qlf_len == 1);
2599
2600         error = xfs_read_buf(mp, mp->m_ddev_targp,
2601                              dq_f->qlf_blkno,
2602                              XFS_FSB_TO_BB(mp, dq_f->qlf_len),
2603                              0, &bp);
2604         if (error) {
2605                 xfs_ioerror_alert("xlog_recover_do..(read#3)", mp,
2606                                   bp, dq_f->qlf_blkno);
2607                 return error;
2608         }
2609         ASSERT(bp);
2610         ddq = (xfs_disk_dquot_t *)xfs_buf_offset(bp, dq_f->qlf_boffset);
2611
2612         /*
2613          * At least the magic num portion should be on disk because this
2614          * was among a chunk of dquots created earlier, and we did some
2615          * minimal initialization then.
2616          */
2617         if (xfs_qm_dqcheck(ddq, dq_f->qlf_id, 0, XFS_QMOPT_DOWARN,
2618                            "xlog_recover_do_dquot_trans")) {
2619                 xfs_buf_relse(bp);
2620                 return XFS_ERROR(EIO);
2621         }
2622
2623         memcpy(ddq, recddq, item->ri_buf[1].i_len);
2624
2625         ASSERT(dq_f->qlf_size == 2);
2626         ASSERT(XFS_BUF_FSPRIVATE(bp, void *) == NULL ||
2627                XFS_BUF_FSPRIVATE(bp, xfs_mount_t *) == mp);
2628         XFS_BUF_SET_FSPRIVATE(bp, mp);
2629         XFS_BUF_SET_IODONE_FUNC(bp, xlog_recover_iodone);
2630         xfs_bdwrite(mp, bp);
2631
2632         return (0);
2633 }
2634
2635 /*
2636  * This routine is called to create an in-core extent free intent
2637  * item from the efi format structure which was logged on disk.
2638  * It allocates an in-core efi, copies the extents from the format
2639  * structure into it, and adds the efi to the AIL with the given
2640  * LSN.
2641  */
2642 STATIC int
2643 xlog_recover_do_efi_trans(
2644         xlog_t                  *log,
2645         xlog_recover_item_t     *item,
2646         xfs_lsn_t               lsn,
2647         int                     pass)
2648 {
2649         int                     error;
2650         xfs_mount_t             *mp;
2651         xfs_efi_log_item_t      *efip;
2652         xfs_efi_log_format_t    *efi_formatp;
2653
2654         if (pass == XLOG_RECOVER_PASS1) {
2655                 return 0;
2656         }
2657
2658         efi_formatp = (xfs_efi_log_format_t *)item->ri_buf[0].i_addr;
2659
2660         mp = log->l_mp;
2661         efip = xfs_efi_init(mp, efi_formatp->efi_nextents);
2662         if ((error = xfs_efi_copy_format(&(item->ri_buf[0]),
2663                                          &(efip->efi_format)))) {
2664                 xfs_efi_item_free(efip);
2665                 return error;
2666         }
2667         efip->efi_next_extent = efi_formatp->efi_nextents;
2668         efip->efi_flags |= XFS_EFI_COMMITTED;
2669
2670         spin_lock(&log->l_ailp->xa_lock);
2671         /*
2672          * xfs_trans_ail_update() drops the AIL lock.
2673          */
2674         xfs_trans_ail_update(log->l_ailp, (xfs_log_item_t *)efip, lsn);
2675         return 0;
2676 }
2677
2678
2679 /*
2680  * This routine is called when an efd format structure is found in
2681  * a committed transaction in the log.  It's purpose is to cancel
2682  * the corresponding efi if it was still in the log.  To do this
2683  * it searches the AIL for the efi with an id equal to that in the
2684  * efd format structure.  If we find it, we remove the efi from the
2685  * AIL and free it.
2686  */
2687 STATIC void
2688 xlog_recover_do_efd_trans(
2689         xlog_t                  *log,
2690         xlog_recover_item_t     *item,
2691         int                     pass)
2692 {
2693         xfs_efd_log_format_t    *efd_formatp;
2694         xfs_efi_log_item_t      *efip = NULL;
2695         xfs_log_item_t          *lip;
2696         __uint64_t              efi_id;
2697         struct xfs_ail_cursor   cur;
2698         struct xfs_ail          *ailp = log->l_ailp;
2699
2700         if (pass == XLOG_RECOVER_PASS1) {
2701                 return;
2702         }
2703
2704         efd_formatp = (xfs_efd_log_format_t *)item->ri_buf[0].i_addr;
2705         ASSERT((item->ri_buf[0].i_len == (sizeof(xfs_efd_log_format_32_t) +
2706                 ((efd_formatp->efd_nextents - 1) * sizeof(xfs_extent_32_t)))) ||
2707                (item->ri_buf[0].i_len == (sizeof(xfs_efd_log_format_64_t) +
2708                 ((efd_formatp->efd_nextents - 1) * sizeof(xfs_extent_64_t)))));
2709         efi_id = efd_formatp->efd_efi_id;
2710
2711         /*
2712          * Search for the efi with the id in the efd format structure
2713          * in the AIL.
2714          */
2715         spin_lock(&ailp->xa_lock);
2716         lip = xfs_trans_ail_cursor_first(ailp, &cur, 0);
2717         while (lip != NULL) {
2718                 if (lip->li_type == XFS_LI_EFI) {
2719                         efip = (xfs_efi_log_item_t *)lip;
2720                         if (efip->efi_format.efi_id == efi_id) {
2721                                 /*
2722                                  * xfs_trans_ail_delete() drops the
2723                                  * AIL lock.
2724                                  */
2725                                 xfs_trans_ail_delete(ailp, lip);
2726                                 xfs_efi_item_free(efip);
2727                                 spin_lock(&ailp->xa_lock);
2728                                 break;
2729                         }
2730                 }
2731                 lip = xfs_trans_ail_cursor_next(ailp, &cur);
2732         }
2733         xfs_trans_ail_cursor_done(ailp, &cur);
2734         spin_unlock(&ailp->xa_lock);
2735 }
2736
2737 /*
2738  * Perform the transaction
2739  *
2740  * If the transaction modifies a buffer or inode, do it now.  Otherwise,
2741  * EFIs and EFDs get queued up by adding entries into the AIL for them.
2742  */
2743 STATIC int
2744 xlog_recover_do_trans(
2745         xlog_t                  *log,
2746         xlog_recover_t          *trans,
2747         int                     pass)
2748 {
2749         int                     error = 0;
2750         xlog_recover_item_t     *item, *first_item;
2751
2752         if ((error = xlog_recover_reorder_trans(trans)))
2753                 return error;
2754         first_item = item = trans->r_itemq;
2755         do {
2756                 /*
2757                  * we don't need to worry about the block number being
2758                  * truncated in > 1 TB buffers because in user-land,
2759                  * we're now n32 or 64-bit so xfs_daddr_t is 64-bits so
2760                  * the blknos will get through the user-mode buffer
2761                  * cache properly.  The only bad case is o32 kernels
2762                  * where xfs_daddr_t is 32-bits but mount will warn us
2763                  * off a > 1 TB filesystem before we get here.
2764                  */
2765                 if ((ITEM_TYPE(item) == XFS_LI_BUF)) {
2766                         if  ((error = xlog_recover_do_buffer_trans(log, item,
2767                                                                  pass)))
2768                                 break;
2769                 } else if ((ITEM_TYPE(item) == XFS_LI_INODE)) {
2770                         if ((error = xlog_recover_do_inode_trans(log, item,
2771                                                                 pass)))
2772                                 break;
2773                 } else if (ITEM_TYPE(item) == XFS_LI_EFI) {
2774                         if ((error = xlog_recover_do_efi_trans(log, item, trans->r_lsn,
2775                                                   pass)))
2776                                 break;
2777                 } else if (ITEM_TYPE(item) == XFS_LI_EFD) {
2778                         xlog_recover_do_efd_trans(log, item, pass);
2779                 } else if (ITEM_TYPE(item) == XFS_LI_DQUOT) {
2780                         if ((error = xlog_recover_do_dquot_trans(log, item,
2781                                                                    pass)))
2782                                         break;
2783                 } else if ((ITEM_TYPE(item) == XFS_LI_QUOTAOFF)) {
2784                         if ((error = xlog_recover_do_quotaoff_trans(log, item,
2785                                                                    pass)))
2786                                         break;
2787                 } else {
2788                         xlog_warn("XFS: xlog_recover_do_trans");
2789                         ASSERT(0);
2790                         error = XFS_ERROR(EIO);
2791                         break;
2792                 }
2793                 item = item->ri_next;
2794         } while (first_item != item);
2795
2796         return error;
2797 }
2798
2799 /*
2800  * Free up any resources allocated by the transaction
2801  *
2802  * Remember that EFIs, EFDs, and IUNLINKs are handled later.
2803  */
2804 STATIC void
2805 xlog_recover_free_trans(
2806         xlog_recover_t          *trans)
2807 {
2808         xlog_recover_item_t     *first_item, *item, *free_item;
2809         int                     i;
2810
2811         item = first_item = trans->r_itemq;
2812         do {
2813                 free_item = item;
2814                 item = item->ri_next;
2815                  /* Free the regions in the item. */
2816                 for (i = 0; i < free_item->ri_cnt; i++) {
2817                         kmem_free(free_item->ri_buf[i].i_addr);
2818                 }
2819                 /* Free the item itself */
2820                 kmem_free(free_item->ri_buf);
2821                 kmem_free(free_item);
2822         } while (first_item != item);
2823         /* Free the transaction recover structure */
2824         kmem_free(trans);
2825 }
2826
2827 STATIC int
2828 xlog_recover_commit_trans(
2829         xlog_t                  *log,
2830         xlog_recover_t          **q,
2831         xlog_recover_t          *trans,
2832         int                     pass)
2833 {
2834         int                     error;
2835
2836         if ((error = xlog_recover_unlink_tid(q, trans)))
2837                 return error;
2838         if ((error = xlog_recover_do_trans(log, trans, pass)))
2839                 return error;
2840         xlog_recover_free_trans(trans);                 /* no error */
2841         return 0;
2842 }
2843
2844 STATIC int
2845 xlog_recover_unmount_trans(
2846         xlog_recover_t          *trans)
2847 {
2848         /* Do nothing now */
2849         xlog_warn("XFS: xlog_recover_unmount_trans: Unmount LR");
2850         return 0;
2851 }
2852
2853 /*
2854  * There are two valid states of the r_state field.  0 indicates that the
2855  * transaction structure is in a normal state.  We have either seen the
2856  * start of the transaction or the last operation we added was not a partial
2857  * operation.  If the last operation we added to the transaction was a
2858  * partial operation, we need to mark r_state with XLOG_WAS_CONT_TRANS.
2859  *
2860  * NOTE: skip LRs with 0 data length.
2861  */
2862 STATIC int
2863 xlog_recover_process_data(
2864         xlog_t                  *log,
2865         xlog_recover_t          *rhash[],
2866         xlog_rec_header_t       *rhead,
2867         xfs_caddr_t             dp,
2868         int                     pass)
2869 {
2870         xfs_caddr_t             lp;
2871         int                     num_logops;
2872         xlog_op_header_t        *ohead;
2873         xlog_recover_t          *trans;
2874         xlog_tid_t              tid;
2875         int                     error;
2876         unsigned long           hash;
2877         uint                    flags;
2878
2879         lp = dp + be32_to_cpu(rhead->h_len);
2880         num_logops = be32_to_cpu(rhead->h_num_logops);
2881
2882         /* check the log format matches our own - else we can't recover */
2883         if (xlog_header_check_recover(log->l_mp, rhead))
2884                 return (XFS_ERROR(EIO));
2885
2886         while ((dp < lp) && num_logops) {
2887                 ASSERT(dp + sizeof(xlog_op_header_t) <= lp);
2888                 ohead = (xlog_op_header_t *)dp;
2889                 dp += sizeof(xlog_op_header_t);
2890                 if (ohead->oh_clientid != XFS_TRANSACTION &&
2891                     ohead->oh_clientid != XFS_LOG) {
2892                         xlog_warn(
2893                 "XFS: xlog_recover_process_data: bad clientid");
2894                         ASSERT(0);
2895                         return (XFS_ERROR(EIO));
2896                 }
2897                 tid = be32_to_cpu(ohead->oh_tid);
2898                 hash = XLOG_RHASH(tid);
2899                 trans = xlog_recover_find_tid(rhash[hash], tid);
2900                 if (trans == NULL) {               /* not found; add new tid */
2901                         if (ohead->oh_flags & XLOG_START_TRANS)
2902                                 xlog_recover_new_tid(&rhash[hash], tid,
2903                                         be64_to_cpu(rhead->h_lsn));
2904                 } else {
2905                         if (dp + be32_to_cpu(ohead->oh_len) > lp) {
2906                                 xlog_warn(
2907                         "XFS: xlog_recover_process_data: bad length");
2908                                 WARN_ON(1);
2909                                 return (XFS_ERROR(EIO));
2910                         }
2911                         flags = ohead->oh_flags & ~XLOG_END_TRANS;
2912                         if (flags & XLOG_WAS_CONT_TRANS)
2913                                 flags &= ~XLOG_CONTINUE_TRANS;
2914                         switch (flags) {
2915                         case XLOG_COMMIT_TRANS:
2916                                 error = xlog_recover_commit_trans(log,
2917                                                 &rhash[hash], trans, pass);
2918                                 break;
2919                         case XLOG_UNMOUNT_TRANS:
2920                                 error = xlog_recover_unmount_trans(trans);
2921                                 break;
2922                         case XLOG_WAS_CONT_TRANS:
2923                                 error = xlog_recover_add_to_cont_trans(trans,
2924                                                 dp, be32_to_cpu(ohead->oh_len));
2925                                 break;
2926                         case XLOG_START_TRANS:
2927                                 xlog_warn(
2928                         "XFS: xlog_recover_process_data: bad transaction");
2929                                 ASSERT(0);
2930                                 error = XFS_ERROR(EIO);
2931                                 break;
2932                         case 0:
2933                         case XLOG_CONTINUE_TRANS:
2934                                 error = xlog_recover_add_to_trans(trans,
2935                                                 dp, be32_to_cpu(ohead->oh_len));
2936                                 break;
2937                         default:
2938                                 xlog_warn(
2939                         "XFS: xlog_recover_process_data: bad flag");
2940                                 ASSERT(0);
2941                                 error = XFS_ERROR(EIO);
2942                                 break;
2943                         }
2944                         if (error)
2945                                 return error;
2946                 }
2947                 dp += be32_to_cpu(ohead->oh_len);
2948                 num_logops--;
2949         }
2950         return 0;
2951 }
2952
2953 /*
2954  * Process an extent free intent item that was recovered from
2955  * the log.  We need to free the extents that it describes.
2956  */
2957 STATIC int
2958 xlog_recover_process_efi(
2959         xfs_mount_t             *mp,
2960         xfs_efi_log_item_t      *efip)
2961 {
2962         xfs_efd_log_item_t      *efdp;
2963         xfs_trans_t             *tp;
2964         int                     i;
2965         int                     error = 0;
2966         xfs_extent_t            *extp;
2967         xfs_fsblock_t           startblock_fsb;
2968
2969         ASSERT(!(efip->efi_flags & XFS_EFI_RECOVERED));
2970
2971         /*
2972          * First check the validity of the extents described by the
2973          * EFI.  If any are bad, then assume that all are bad and
2974          * just toss the EFI.
2975          */
2976         for (i = 0; i < efip->efi_format.efi_nextents; i++) {
2977                 extp = &(efip->efi_format.efi_extents[i]);
2978                 startblock_fsb = XFS_BB_TO_FSB(mp,
2979                                    XFS_FSB_TO_DADDR(mp, extp->ext_start));
2980                 if ((startblock_fsb == 0) ||
2981                     (extp->ext_len == 0) ||
2982                     (startblock_fsb >= mp->m_sb.sb_dblocks) ||
2983                     (extp->ext_len >= mp->m_sb.sb_agblocks)) {
2984                         /*
2985                          * This will pull the EFI from the AIL and
2986                          * free the memory associated with it.
2987                          */
2988                         xfs_efi_release(efip, efip->efi_format.efi_nextents);
2989                         return XFS_ERROR(EIO);
2990                 }
2991         }
2992
2993         tp = xfs_trans_alloc(mp, 0);
2994         error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0, 0, 0);
2995         if (error)
2996                 goto abort_error;
2997         efdp = xfs_trans_get_efd(tp, efip, efip->efi_format.efi_nextents);
2998
2999         for (i = 0; i < efip->efi_format.efi_nextents; i++) {
3000                 extp = &(efip->efi_format.efi_extents[i]);
3001                 error = xfs_free_extent(tp, extp->ext_start, extp->ext_len);
3002                 if (error)
3003                         goto abort_error;
3004                 xfs_trans_log_efd_extent(tp, efdp, extp->ext_start,
3005                                          extp->ext_len);
3006         }
3007
3008         efip->efi_flags |= XFS_EFI_RECOVERED;
3009         error = xfs_trans_commit(tp, 0);
3010         return error;
3011
3012 abort_error:
3013         xfs_trans_cancel(tp, XFS_TRANS_ABORT);
3014         return error;
3015 }
3016
3017 /*
3018  * When this is called, all of the EFIs which did not have
3019  * corresponding EFDs should be in the AIL.  What we do now
3020  * is free the extents associated with each one.
3021  *
3022  * Since we process the EFIs in normal transactions, they
3023  * will be removed at some point after the commit.  This prevents
3024  * us from just walking down the list processing each one.
3025  * We'll use a flag in the EFI to skip those that we've already
3026  * processed and use the AIL iteration mechanism's generation
3027  * count to try to speed this up at least a bit.
3028  *
3029  * When we start, we know that the EFIs are the only things in
3030  * the AIL.  As we process them, however, other items are added
3031  * to the AIL.  Since everything added to the AIL must come after
3032  * everything already in the AIL, we stop processing as soon as
3033  * we see something other than an EFI in the AIL.
3034  */
3035 STATIC int
3036 xlog_recover_process_efis(
3037         xlog_t                  *log)
3038 {
3039         xfs_log_item_t          *lip;
3040         xfs_efi_log_item_t      *efip;
3041         int                     error = 0;
3042         struct xfs_ail_cursor   cur;
3043         struct xfs_ail          *ailp;
3044
3045         ailp = log->l_ailp;
3046         spin_lock(&ailp->xa_lock);
3047         lip = xfs_trans_ail_cursor_first(ailp, &cur, 0);
3048         while (lip != NULL) {
3049                 /*
3050                  * We're done when we see something other than an EFI.
3051                  * There should be no EFIs left in the AIL now.
3052                  */
3053                 if (lip->li_type != XFS_LI_EFI) {
3054 #ifdef DEBUG
3055                         for (; lip; lip = xfs_trans_ail_cursor_next(ailp, &cur))
3056                                 ASSERT(lip->li_type != XFS_LI_EFI);
3057 #endif
3058                         break;
3059                 }
3060
3061                 /*
3062                  * Skip EFIs that we've already processed.
3063                  */
3064                 efip = (xfs_efi_log_item_t *)lip;
3065                 if (efip->efi_flags & XFS_EFI_RECOVERED) {
3066                         lip = xfs_trans_ail_cursor_next(ailp, &cur);
3067                         continue;
3068                 }
3069
3070                 spin_unlock(&ailp->xa_lock);
3071                 error = xlog_recover_process_efi(log->l_mp, efip);
3072                 spin_lock(&ailp->xa_lock);
3073                 if (error)
3074                         goto out;
3075                 lip = xfs_trans_ail_cursor_next(ailp, &cur);
3076         }
3077 out:
3078         xfs_trans_ail_cursor_done(ailp, &cur);
3079         spin_unlock(&ailp->xa_lock);
3080         return error;
3081 }
3082
3083 /*
3084  * This routine performs a transaction to null out a bad inode pointer
3085  * in an agi unlinked inode hash bucket.
3086  */
3087 STATIC void
3088 xlog_recover_clear_agi_bucket(
3089         xfs_mount_t     *mp,
3090         xfs_agnumber_t  agno,
3091         int             bucket)
3092 {
3093         xfs_trans_t     *tp;
3094         xfs_agi_t       *agi;
3095         xfs_buf_t       *agibp;
3096         int             offset;
3097         int             error;
3098
3099         tp = xfs_trans_alloc(mp, XFS_TRANS_CLEAR_AGI_BUCKET);
3100         error = xfs_trans_reserve(tp, 0, XFS_CLEAR_AGI_BUCKET_LOG_RES(mp),
3101                                   0, 0, 0);
3102         if (error)
3103                 goto out_abort;
3104
3105         error = xfs_read_agi(mp, tp, agno, &agibp);
3106         if (error)
3107                 goto out_abort;
3108
3109         agi = XFS_BUF_TO_AGI(agibp);
3110         agi->agi_unlinked[bucket] = cpu_to_be32(NULLAGINO);
3111         offset = offsetof(xfs_agi_t, agi_unlinked) +
3112                  (sizeof(xfs_agino_t) * bucket);
3113         xfs_trans_log_buf(tp, agibp, offset,
3114                           (offset + sizeof(xfs_agino_t) - 1));
3115
3116         error = xfs_trans_commit(tp, 0);
3117         if (error)
3118                 goto out_error;
3119         return;
3120
3121 out_abort:
3122         xfs_trans_cancel(tp, XFS_TRANS_ABORT);
3123 out_error:
3124         xfs_fs_cmn_err(CE_WARN, mp, "xlog_recover_clear_agi_bucket: "
3125                         "failed to clear agi %d. Continuing.", agno);
3126         return;
3127 }
3128
3129 STATIC xfs_agino_t
3130 xlog_recover_process_one_iunlink(
3131         struct xfs_mount                *mp,
3132         xfs_agnumber_t                  agno,
3133         xfs_agino_t                     agino,
3134         int                             bucket)
3135 {
3136         struct xfs_buf                  *ibp;
3137         struct xfs_dinode               *dip;
3138         struct xfs_inode                *ip;
3139         xfs_ino_t                       ino;
3140         int                             error;
3141
3142         ino = XFS_AGINO_TO_INO(mp, agno, agino);
3143         error = xfs_iget(mp, NULL, ino, 0, 0, &ip, 0);
3144         if (error)
3145                 goto fail;
3146
3147         /*
3148          * Get the on disk inode to find the next inode in the bucket.
3149          */
3150         error = xfs_itobp(mp, NULL, ip, &dip, &ibp, XFS_BUF_LOCK);
3151         if (error)
3152                 goto fail_iput;
3153
3154         ASSERT(ip->i_d.di_nlink == 0);
3155         ASSERT(ip->i_d.di_mode != 0);
3156
3157         /* setup for the next pass */
3158         agino = be32_to_cpu(dip->di_next_unlinked);
3159         xfs_buf_relse(ibp);
3160
3161         /*
3162          * Prevent any DMAPI event from being sent when the reference on
3163          * the inode is dropped.
3164          */
3165         ip->i_d.di_dmevmask = 0;
3166
3167         IRELE(ip);
3168         return agino;
3169
3170  fail_iput:
3171         IRELE(ip);
3172  fail:
3173         /*
3174          * We can't read in the inode this bucket points to, or this inode
3175          * is messed up.  Just ditch this bucket of inodes.  We will lose
3176          * some inodes and space, but at least we won't hang.
3177          *
3178          * Call xlog_recover_clear_agi_bucket() to perform a transaction to
3179          * clear the inode pointer in the bucket.
3180          */
3181         xlog_recover_clear_agi_bucket(mp, agno, bucket);
3182         return NULLAGINO;
3183 }
3184
3185 /*
3186  * xlog_iunlink_recover
3187  *
3188  * This is called during recovery to process any inodes which
3189  * we unlinked but not freed when the system crashed.  These
3190  * inodes will be on the lists in the AGI blocks.  What we do
3191  * here is scan all the AGIs and fully truncate and free any
3192  * inodes found on the lists.  Each inode is removed from the
3193  * lists when it has been fully truncated and is freed.  The
3194  * freeing of the inode and its removal from the list must be
3195  * atomic.
3196  */
3197 void
3198 xlog_recover_process_iunlinks(
3199         xlog_t          *log)
3200 {
3201         xfs_mount_t     *mp;
3202         xfs_agnumber_t  agno;
3203         xfs_agi_t       *agi;
3204         xfs_buf_t       *agibp;
3205         xfs_agino_t     agino;
3206         int             bucket;
3207         int             error;
3208         uint            mp_dmevmask;
3209
3210         mp = log->l_mp;
3211
3212         /*
3213          * Prevent any DMAPI event from being sent while in this function.
3214          */
3215         mp_dmevmask = mp->m_dmevmask;
3216         mp->m_dmevmask = 0;
3217
3218         for (agno = 0; agno < mp->m_sb.sb_agcount; agno++) {
3219                 /*
3220                  * Find the agi for this ag.
3221                  */
3222                 error = xfs_read_agi(mp, NULL, agno, &agibp);
3223                 if (error) {
3224                         /*
3225                          * AGI is b0rked. Don't process it.
3226                          *
3227                          * We should probably mark the filesystem as corrupt
3228                          * after we've recovered all the ag's we can....
3229                          */
3230                         continue;
3231                 }
3232                 agi = XFS_BUF_TO_AGI(agibp);
3233
3234                 for (bucket = 0; bucket < XFS_AGI_UNLINKED_BUCKETS; bucket++) {
3235                         agino = be32_to_cpu(agi->agi_unlinked[bucket]);
3236                         while (agino != NULLAGINO) {
3237                                 /*
3238                                  * Release the agi buffer so that it can
3239                                  * be acquired in the normal course of the
3240                                  * transaction to truncate and free the inode.
3241                                  */
3242                                 xfs_buf_relse(agibp);
3243
3244                                 agino = xlog_recover_process_one_iunlink(mp,
3245                                                         agno, agino, bucket);
3246
3247                                 /*
3248                                  * Reacquire the agibuffer and continue around
3249                                  * the loop. This should never fail as we know
3250                                  * the buffer was good earlier on.
3251                                  */
3252                                 error = xfs_read_agi(mp, NULL, agno, &agibp);
3253                                 ASSERT(error == 0);
3254                                 agi = XFS_BUF_TO_AGI(agibp);
3255                         }
3256                 }
3257
3258                 /*
3259                  * Release the buffer for the current agi so we can
3260                  * go on to the next one.
3261                  */
3262                 xfs_buf_relse(agibp);
3263         }
3264
3265         mp->m_dmevmask = mp_dmevmask;
3266 }
3267
3268
3269 #ifdef DEBUG
3270 STATIC void
3271 xlog_pack_data_checksum(
3272         xlog_t          *log,
3273         xlog_in_core_t  *iclog,
3274         int             size)
3275 {
3276         int             i;
3277         __be32          *up;
3278         uint            chksum = 0;
3279
3280         up = (__be32 *)iclog->ic_datap;
3281         /* divide length by 4 to get # words */
3282         for (i = 0; i < (size >> 2); i++) {
3283                 chksum ^= be32_to_cpu(*up);
3284                 up++;
3285         }
3286         iclog->ic_header.h_chksum = cpu_to_be32(chksum);
3287 }
3288 #else
3289 #define xlog_pack_data_checksum(log, iclog, size)
3290 #endif
3291
3292 /*
3293  * Stamp cycle number in every block
3294  */
3295 void
3296 xlog_pack_data(
3297         xlog_t                  *log,
3298         xlog_in_core_t          *iclog,
3299         int                     roundoff)
3300 {
3301         int                     i, j, k;
3302         int                     size = iclog->ic_offset + roundoff;
3303         __be32                  cycle_lsn;
3304         xfs_caddr_t             dp;
3305
3306         xlog_pack_data_checksum(log, iclog, size);
3307
3308         cycle_lsn = CYCLE_LSN_DISK(iclog->ic_header.h_lsn);
3309
3310         dp = iclog->ic_datap;
3311         for (i = 0; i < BTOBB(size) &&
3312                 i < (XLOG_HEADER_CYCLE_SIZE / BBSIZE); i++) {
3313                 iclog->ic_header.h_cycle_data[i] = *(__be32 *)dp;
3314                 *(__be32 *)dp = cycle_lsn;
3315                 dp += BBSIZE;
3316         }
3317
3318         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) {
3319                 xlog_in_core_2_t *xhdr = iclog->ic_data;
3320
3321                 for ( ; i < BTOBB(size); i++) {
3322                         j = i / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3323                         k = i % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3324                         xhdr[j].hic_xheader.xh_cycle_data[k] = *(__be32 *)dp;
3325                         *(__be32 *)dp = cycle_lsn;
3326                         dp += BBSIZE;
3327                 }
3328
3329                 for (i = 1; i < log->l_iclog_heads; i++) {
3330                         xhdr[i].hic_xheader.xh_cycle = cycle_lsn;
3331                 }
3332         }
3333 }
3334
3335 #if defined(DEBUG) && defined(XFS_LOUD_RECOVERY)
3336 STATIC void
3337 xlog_unpack_data_checksum(
3338         xlog_rec_header_t       *rhead,
3339         xfs_caddr_t             dp,
3340         xlog_t                  *log)
3341 {
3342         __be32                  *up = (__be32 *)dp;
3343         uint                    chksum = 0;
3344         int                     i;
3345
3346         /* divide length by 4 to get # words */
3347         for (i=0; i < be32_to_cpu(rhead->h_len) >> 2; i++) {
3348                 chksum ^= be32_to_cpu(*up);
3349                 up++;
3350         }
3351         if (chksum != be32_to_cpu(rhead->h_chksum)) {
3352             if (rhead->h_chksum ||
3353                 ((log->l_flags & XLOG_CHKSUM_MISMATCH) == 0)) {
3354                     cmn_err(CE_DEBUG,
3355                         "XFS: LogR chksum mismatch: was (0x%x) is (0x%x)\n",
3356                             be32_to_cpu(rhead->h_chksum), chksum);
3357                     cmn_err(CE_DEBUG,
3358 "XFS: Disregard message if filesystem was created with non-DEBUG kernel");
3359                     if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) {
3360                             cmn_err(CE_DEBUG,
3361                                 "XFS: LogR this is a LogV2 filesystem\n");
3362                     }
3363                     log->l_flags |= XLOG_CHKSUM_MISMATCH;
3364             }
3365         }
3366 }
3367 #else
3368 #define xlog_unpack_data_checksum(rhead, dp, log)
3369 #endif
3370
3371 STATIC void
3372 xlog_unpack_data(
3373         xlog_rec_header_t       *rhead,
3374         xfs_caddr_t             dp,
3375         xlog_t                  *log)
3376 {
3377         int                     i, j, k;
3378
3379         for (i = 0; i < BTOBB(be32_to_cpu(rhead->h_len)) &&
3380                   i < (XLOG_HEADER_CYCLE_SIZE / BBSIZE); i++) {
3381                 *(__be32 *)dp = *(__be32 *)&rhead->h_cycle_data[i];
3382                 dp += BBSIZE;
3383         }
3384
3385         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) {
3386                 xlog_in_core_2_t *xhdr = (xlog_in_core_2_t *)rhead;
3387                 for ( ; i < BTOBB(be32_to_cpu(rhead->h_len)); i++) {
3388                         j = i / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3389                         k = i % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3390                         *(__be32 *)dp = xhdr[j].hic_xheader.xh_cycle_data[k];
3391                         dp += BBSIZE;
3392                 }
3393         }
3394
3395         xlog_unpack_data_checksum(rhead, dp, log);
3396 }
3397
3398 STATIC int
3399 xlog_valid_rec_header(
3400         xlog_t                  *log,
3401         xlog_rec_header_t       *rhead,
3402         xfs_daddr_t             blkno)
3403 {
3404         int                     hlen;
3405
3406         if (unlikely(be32_to_cpu(rhead->h_magicno) != XLOG_HEADER_MAGIC_NUM)) {
3407                 XFS_ERROR_REPORT("xlog_valid_rec_header(1)",
3408                                 XFS_ERRLEVEL_LOW, log->l_mp);
3409                 return XFS_ERROR(EFSCORRUPTED);
3410         }
3411         if (unlikely(
3412             (!rhead->h_version ||
3413             (be32_to_cpu(rhead->h_version) & (~XLOG_VERSION_OKBITS))))) {
3414                 xlog_warn("XFS: %s: unrecognised log version (%d).",
3415                         __func__, be32_to_cpu(rhead->h_version));
3416                 return XFS_ERROR(EIO);
3417         }
3418
3419         /* LR body must have data or it wouldn't have been written */
3420         hlen = be32_to_cpu(rhead->h_len);
3421         if (unlikely( hlen <= 0 || hlen > INT_MAX )) {
3422                 XFS_ERROR_REPORT("xlog_valid_rec_header(2)",
3423                                 XFS_ERRLEVEL_LOW, log->l_mp);
3424                 return XFS_ERROR(EFSCORRUPTED);
3425         }
3426         if (unlikely( blkno > log->l_logBBsize || blkno > INT_MAX )) {
3427                 XFS_ERROR_REPORT("xlog_valid_rec_header(3)",
3428                                 XFS_ERRLEVEL_LOW, log->l_mp);
3429                 return XFS_ERROR(EFSCORRUPTED);
3430         }
3431         return 0;
3432 }
3433
3434 /*
3435  * Read the log from tail to head and process the log records found.
3436  * Handle the two cases where the tail and head are in the same cycle
3437  * and where the active portion of the log wraps around the end of
3438  * the physical log separately.  The pass parameter is passed through
3439  * to the routines called to process the data and is not looked at
3440  * here.
3441  */
3442 STATIC int
3443 xlog_do_recovery_pass(
3444         xlog_t                  *log,
3445         xfs_daddr_t             head_blk,
3446         xfs_daddr_t             tail_blk,
3447         int                     pass)
3448 {
3449         xlog_rec_header_t       *rhead;
3450         xfs_daddr_t             blk_no;
3451         xfs_caddr_t             bufaddr, offset;
3452         xfs_buf_t               *hbp, *dbp;
3453         int                     error = 0, h_size;
3454         int                     bblks, split_bblks;
3455         int                     hblks, split_hblks, wrapped_hblks;
3456         xlog_recover_t          *rhash[XLOG_RHASH_SIZE];
3457
3458         ASSERT(head_blk != tail_blk);
3459
3460         /*
3461          * Read the header of the tail block and get the iclog buffer size from
3462          * h_size.  Use this to tell how many sectors make up the log header.
3463          */
3464         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb)) {
3465                 /*
3466                  * When using variable length iclogs, read first sector of
3467                  * iclog header and extract the header size from it.  Get a
3468                  * new hbp that is the correct size.
3469                  */
3470                 hbp = xlog_get_bp(log, 1);
3471                 if (!hbp)
3472                         return ENOMEM;
3473                 if ((error = xlog_bread(log, tail_blk, 1, hbp)))
3474                         goto bread_err1;
3475                 offset = xlog_align(log, tail_blk, 1, hbp);
3476                 rhead = (xlog_rec_header_t *)offset;
3477                 error = xlog_valid_rec_header(log, rhead, tail_blk);
3478                 if (error)
3479                         goto bread_err1;
3480                 h_size = be32_to_cpu(rhead->h_size);
3481                 if ((be32_to_cpu(rhead->h_version) & XLOG_VERSION_2) &&
3482                     (h_size > XLOG_HEADER_CYCLE_SIZE)) {
3483                         hblks = h_size / XLOG_HEADER_CYCLE_SIZE;
3484                         if (h_size % XLOG_HEADER_CYCLE_SIZE)
3485                                 hblks++;
3486                         xlog_put_bp(hbp);
3487                         hbp = xlog_get_bp(log, hblks);
3488                 } else {
3489                         hblks = 1;
3490                 }
3491         } else {
3492                 ASSERT(log->l_sectbb_log == 0);
3493                 hblks = 1;
3494                 hbp = xlog_get_bp(log, 1);
3495                 h_size = XLOG_BIG_RECORD_BSIZE;
3496         }
3497
3498         if (!hbp)
3499                 return ENOMEM;
3500         dbp = xlog_get_bp(log, BTOBB(h_size));
3501         if (!dbp) {
3502                 xlog_put_bp(hbp);
3503                 return ENOMEM;
3504         }
3505
3506         memset(rhash, 0, sizeof(rhash));
3507         if (tail_blk <= head_blk) {
3508                 for (blk_no = tail_blk; blk_no < head_blk; ) {
3509                         if ((error = xlog_bread(log, blk_no, hblks, hbp)))
3510                                 goto bread_err2;
3511                         offset = xlog_align(log, blk_no, hblks, hbp);
3512                         rhead = (xlog_rec_header_t *)offset;
3513                         error = xlog_valid_rec_header(log, rhead, blk_no);
3514                         if (error)
3515                                 goto bread_err2;
3516
3517                         /* blocks in data section */
3518                         bblks = (int)BTOBB(be32_to_cpu(rhead->h_len));
3519                         error = xlog_bread(log, blk_no + hblks, bblks, dbp);
3520                         if (error)
3521                                 goto bread_err2;
3522                         offset = xlog_align(log, blk_no + hblks, bblks, dbp);
3523                         xlog_unpack_data(rhead, offset, log);
3524                         if ((error = xlog_recover_process_data(log,
3525                                                 rhash, rhead, offset, pass)))
3526                                 goto bread_err2;
3527                         blk_no += bblks + hblks;
3528                 }
3529         } else {
3530                 /*
3531                  * Perform recovery around the end of the physical log.
3532                  * When the head is not on the same cycle number as the tail,
3533                  * we can't do a sequential recovery as above.
3534                  */
3535                 blk_no = tail_blk;
3536                 while (blk_no < log->l_logBBsize) {
3537                         /*
3538                          * Check for header wrapping around physical end-of-log
3539                          */
3540                         offset = NULL;
3541                         split_hblks = 0;
3542                         wrapped_hblks = 0;
3543                         if (blk_no + hblks <= log->l_logBBsize) {
3544                                 /* Read header in one read */
3545                                 error = xlog_bread(log, blk_no, hblks, hbp);
3546                                 if (error)
3547                                         goto bread_err2;
3548                                 offset = xlog_align(log, blk_no, hblks, hbp);
3549                         } else {
3550                                 /* This LR is split across physical log end */
3551                                 if (blk_no != log->l_logBBsize) {
3552                                         /* some data before physical log end */
3553                                         ASSERT(blk_no <= INT_MAX);
3554                                         split_hblks = log->l_logBBsize - (int)blk_no;
3555                                         ASSERT(split_hblks > 0);
3556                                         if ((error = xlog_bread(log, blk_no,
3557                                                         split_hblks, hbp)))
3558                                                 goto bread_err2;
3559                                         offset = xlog_align(log, blk_no,
3560                                                         split_hblks, hbp);
3561                                 }
3562                                 /*
3563                                  * Note: this black magic still works with
3564                                  * large sector sizes (non-512) only because:
3565                                  * - we increased the buffer size originally
3566                                  *   by 1 sector giving us enough extra space
3567                                  *   for the second read;
3568                                  * - the log start is guaranteed to be sector
3569                                  *   aligned;
3570                                  * - we read the log end (LR header start)
3571                                  *   _first_, then the log start (LR header end)
3572                                  *   - order is important.
3573                                  */
3574                                 wrapped_hblks = hblks - split_hblks;
3575                                 bufaddr = XFS_BUF_PTR(hbp);
3576                                 error = XFS_BUF_SET_PTR(hbp,
3577                                                 bufaddr + BBTOB(split_hblks),
3578                                                 BBTOB(hblks - split_hblks));
3579                                 if (!error)
3580                                         error = xlog_bread(log, 0,
3581                                                         wrapped_hblks, hbp);
3582                                 if (!error)
3583                                         error = XFS_BUF_SET_PTR(hbp, bufaddr,
3584                                                         BBTOB(hblks));
3585                                 if (error)
3586                                         goto bread_err2;
3587                                 if (!offset)
3588                                         offset = xlog_align(log, 0,
3589                                                         wrapped_hblks, hbp);
3590                         }
3591                         rhead = (xlog_rec_header_t *)offset;
3592                         error = xlog_valid_rec_header(log, rhead,
3593                                                 split_hblks ? blk_no : 0);
3594                         if (error)
3595                                 goto bread_err2;
3596
3597                         bblks = (int)BTOBB(be32_to_cpu(rhead->h_len));
3598                         blk_no += hblks;
3599
3600                         /* Read in data for log record */
3601                         if (blk_no + bblks <= log->l_logBBsize) {
3602                                 error = xlog_bread(log, blk_no, bblks, dbp);
3603                                 if (error)
3604                                         goto bread_err2;
3605                                 offset = xlog_align(log, blk_no, bblks, dbp);
3606                         } else {
3607                                 /* This log record is split across the
3608                                  * physical end of log */
3609                                 offset = NULL;
3610                                 split_bblks = 0;
3611                                 if (blk_no != log->l_logBBsize) {
3612                                         /* some data is before the physical
3613                                          * end of log */
3614                                         ASSERT(!wrapped_hblks);
3615                                         ASSERT(blk_no <= INT_MAX);
3616                                         split_bblks =
3617                                                 log->l_logBBsize - (int)blk_no;
3618                                         ASSERT(split_bblks > 0);
3619                                         if ((error = xlog_bread(log, blk_no,
3620                                                         split_bblks, dbp)))
3621                                                 goto bread_err2;
3622                                         offset = xlog_align(log, blk_no,
3623                                                         split_bblks, dbp);
3624                                 }
3625                                 /*
3626                                  * Note: this black magic still works with
3627                                  * large sector sizes (non-512) only because:
3628                                  * - we increased the buffer size originally
3629                                  *   by 1 sector giving us enough extra space
3630                                  *   for the second read;
3631                                  * - the log start is guaranteed to be sector
3632                                  *   aligned;
3633                                  * - we read the log end (LR header start)
3634                                  *   _first_, then the log start (LR header end)
3635                                  *   - order is important.
3636                                  */
3637                                 bufaddr = XFS_BUF_PTR(dbp);
3638                                 error = XFS_BUF_SET_PTR(dbp,
3639                                                 bufaddr + BBTOB(split_bblks),
3640                                                 BBTOB(bblks - split_bblks));
3641                                 if (!error)
3642                                         error = xlog_bread(log, wrapped_hblks,
3643                                                         bblks - split_bblks,
3644                                                         dbp);
3645                                 if (!error)
3646                                         error = XFS_BUF_SET_PTR(dbp, bufaddr,
3647                                                         h_size);
3648                                 if (error)
3649                                         goto bread_err2;
3650                                 if (!offset)
3651                                         offset = xlog_align(log, wrapped_hblks,
3652                                                 bblks - split_bblks, dbp);
3653                         }
3654                         xlog_unpack_data(rhead, offset, log);
3655                         if ((error = xlog_recover_process_data(log, rhash,
3656                                                         rhead, offset, pass)))
3657                                 goto bread_err2;
3658                         blk_no += bblks;
3659                 }
3660
3661                 ASSERT(blk_no >= log->l_logBBsize);
3662                 blk_no -= log->l_logBBsize;
3663
3664                 /* read first part of physical log */
3665                 while (blk_no < head_blk) {
3666                         if ((error = xlog_bread(log, blk_no, hblks, hbp)))
3667                                 goto bread_err2;
3668                         offset = xlog_align(log, blk_no, hblks, hbp);
3669                         rhead = (xlog_rec_header_t *)offset;
3670                         error = xlog_valid_rec_header(log, rhead, blk_no);
3671                         if (error)
3672                                 goto bread_err2;
3673                         bblks = (int)BTOBB(be32_to_cpu(rhead->h_len));
3674                         if ((error = xlog_bread(log, blk_no+hblks, bblks, dbp)))
3675                                 goto bread_err2;
3676                         offset = xlog_align(log, blk_no+hblks, bblks, dbp);
3677                         xlog_unpack_data(rhead, offset, log);
3678                         if ((error = xlog_recover_process_data(log, rhash,
3679                                                         rhead, offset, pass)))
3680                                 goto bread_err2;
3681                         blk_no += bblks + hblks;
3682                 }
3683         }
3684
3685  bread_err2:
3686         xlog_put_bp(dbp);
3687  bread_err1:
3688         xlog_put_bp(hbp);
3689         return error;
3690 }
3691
3692 /*
3693  * Do the recovery of the log.  We actually do this in two phases.
3694  * The two passes are necessary in order to implement the function
3695  * of cancelling a record written into the log.  The first pass
3696  * determines those things which have been cancelled, and the
3697  * second pass replays log items normally except for those which
3698  * have been cancelled.  The handling of the replay and cancellations
3699  * takes place in the log item type specific routines.
3700  *
3701  * The table of items which have cancel records in the log is allocated
3702  * and freed at this level, since only here do we know when all of
3703  * the log recovery has been completed.
3704  */
3705 STATIC int
3706 xlog_do_log_recovery(
3707         xlog_t          *log,
3708         xfs_daddr_t     head_blk,
3709         xfs_daddr_t     tail_blk)
3710 {
3711         int             error;
3712
3713         ASSERT(head_blk != tail_blk);
3714
3715         /*
3716          * First do a pass to find all of the cancelled buf log items.
3717          * Store them in the buf_cancel_table for use in the second pass.
3718          */
3719         log->l_buf_cancel_table =
3720                 (xfs_buf_cancel_t **)kmem_zalloc(XLOG_BC_TABLE_SIZE *
3721                                                  sizeof(xfs_buf_cancel_t*),
3722                                                  KM_SLEEP);
3723         error = xlog_do_recovery_pass(log, head_blk, tail_blk,
3724                                       XLOG_RECOVER_PASS1);
3725         if (error != 0) {
3726                 kmem_free(log->l_buf_cancel_table);
3727                 log->l_buf_cancel_table = NULL;
3728                 return error;
3729         }
3730         /*
3731          * Then do a second pass to actually recover the items in the log.
3732          * When it is complete free the table of buf cancel items.
3733          */
3734         error = xlog_do_recovery_pass(log, head_blk, tail_blk,
3735                                       XLOG_RECOVER_PASS2);
3736 #ifdef DEBUG
3737         if (!error) {
3738                 int     i;
3739
3740                 for (i = 0; i < XLOG_BC_TABLE_SIZE; i++)
3741                         ASSERT(log->l_buf_cancel_table[i] == NULL);
3742         }
3743 #endif  /* DEBUG */
3744
3745         kmem_free(log->l_buf_cancel_table);
3746         log->l_buf_cancel_table = NULL;
3747
3748         return error;
3749 }
3750
3751 /*
3752  * Do the actual recovery
3753  */
3754 STATIC int
3755 xlog_do_recover(
3756         xlog_t          *log,
3757         xfs_daddr_t     head_blk,
3758         xfs_daddr_t     tail_blk)
3759 {
3760         int             error;
3761         xfs_buf_t       *bp;
3762         xfs_sb_t        *sbp;
3763
3764         /*
3765          * First replay the images in the log.
3766          */
3767         error = xlog_do_log_recovery(log, head_blk, tail_blk);
3768         if (error) {
3769                 return error;
3770         }
3771
3772         XFS_bflush(log->l_mp->m_ddev_targp);
3773
3774         /*
3775          * If IO errors happened during recovery, bail out.
3776          */
3777         if (XFS_FORCED_SHUTDOWN(log->l_mp)) {
3778                 return (EIO);
3779         }
3780
3781         /*
3782          * We now update the tail_lsn since much of the recovery has completed
3783          * and there may be space available to use.  If there were no extent
3784          * or iunlinks, we can free up the entire log and set the tail_lsn to
3785          * be the last_sync_lsn.  This was set in xlog_find_tail to be the
3786          * lsn of the last known good LR on disk.  If there are extent frees
3787          * or iunlinks they will have some entries in the AIL; so we look at
3788          * the AIL to determine how to set the tail_lsn.
3789          */
3790         xlog_assign_tail_lsn(log->l_mp);
3791
3792         /*
3793          * Now that we've finished replaying all buffer and inode
3794          * updates, re-read in the superblock.
3795          */
3796         bp = xfs_getsb(log->l_mp, 0);
3797         XFS_BUF_UNDONE(bp);
3798         ASSERT(!(XFS_BUF_ISWRITE(bp)));
3799         ASSERT(!(XFS_BUF_ISDELAYWRITE(bp)));
3800         XFS_BUF_READ(bp);
3801         XFS_BUF_UNASYNC(bp);
3802         xfsbdstrat(log->l_mp, bp);
3803         error = xfs_iowait(bp);
3804         if (error) {
3805                 xfs_ioerror_alert("xlog_do_recover",
3806                                   log->l_mp, bp, XFS_BUF_ADDR(bp));
3807                 ASSERT(0);
3808                 xfs_buf_relse(bp);
3809                 return error;
3810         }
3811
3812         /* Convert superblock from on-disk format */
3813         sbp = &log->l_mp->m_sb;
3814         xfs_sb_from_disk(sbp, XFS_BUF_TO_SBP(bp));
3815         ASSERT(sbp->sb_magicnum == XFS_SB_MAGIC);
3816         ASSERT(xfs_sb_good_version(sbp));
3817         xfs_buf_relse(bp);
3818
3819         /* We've re-read the superblock so re-initialize per-cpu counters */
3820         xfs_icsb_reinit_counters(log->l_mp);
3821
3822         xlog_recover_check_summary(log);
3823
3824         /* Normal transactions can now occur */
3825         log->l_flags &= ~XLOG_ACTIVE_RECOVERY;
3826         return 0;
3827 }
3828
3829 /*
3830  * Perform recovery and re-initialize some log variables in xlog_find_tail.
3831  *
3832  * Return error or zero.
3833  */
3834 int
3835 xlog_recover(
3836         xlog_t          *log)
3837 {
3838         xfs_daddr_t     head_blk, tail_blk;
3839         int             error;
3840
3841         /* find the tail of the log */
3842         if ((error = xlog_find_tail(log, &head_blk, &tail_blk)))
3843                 return error;
3844
3845         if (tail_blk != head_blk) {
3846                 /* There used to be a comment here:
3847                  *
3848                  * disallow recovery on read-only mounts.  note -- mount
3849                  * checks for ENOSPC and turns it into an intelligent
3850                  * error message.
3851                  * ...but this is no longer true.  Now, unless you specify
3852                  * NORECOVERY (in which case this function would never be
3853                  * called), we just go ahead and recover.  We do this all
3854                  * under the vfs layer, so we can get away with it unless
3855                  * the device itself is read-only, in which case we fail.
3856                  */
3857                 if ((error = xfs_dev_is_read_only(log->l_mp, "recovery"))) {
3858                         return error;
3859                 }
3860
3861                 cmn_err(CE_NOTE,
3862                         "Starting XFS recovery on filesystem: %s (logdev: %s)",
3863                         log->l_mp->m_fsname, log->l_mp->m_logname ?
3864                         log->l_mp->m_logname : "internal");
3865
3866                 error = xlog_do_recover(log, head_blk, tail_blk);
3867                 log->l_flags |= XLOG_RECOVERY_NEEDED;
3868         }
3869         return error;
3870 }
3871
3872 /*
3873  * In the first part of recovery we replay inodes and buffers and build
3874  * up the list of extent free items which need to be processed.  Here
3875  * we process the extent free items and clean up the on disk unlinked
3876  * inode lists.  This is separated from the first part of recovery so
3877  * that the root and real-time bitmap inodes can be read in from disk in
3878  * between the two stages.  This is necessary so that we can free space
3879  * in the real-time portion of the file system.
3880  */
3881 int
3882 xlog_recover_finish(
3883         xlog_t          *log)
3884 {
3885         /*
3886          * Now we're ready to do the transactions needed for the
3887          * rest of recovery.  Start with completing all the extent
3888          * free intent records and then process the unlinked inode
3889          * lists.  At this point, we essentially run in normal mode
3890          * except that we're still performing recovery actions
3891          * rather than accepting new requests.
3892          */
3893         if (log->l_flags & XLOG_RECOVERY_NEEDED) {
3894                 int     error;
3895                 error = xlog_recover_process_efis(log);
3896                 if (error) {
3897                         cmn_err(CE_ALERT,
3898                                 "Failed to recover EFIs on filesystem: %s",
3899                                 log->l_mp->m_fsname);
3900                         return error;
3901                 }
3902                 /*
3903                  * Sync the log to get all the EFIs out of the AIL.
3904                  * This isn't absolutely necessary, but it helps in
3905                  * case the unlink transactions would have problems
3906                  * pushing the EFIs out of the way.
3907                  */
3908                 xfs_log_force(log->l_mp, (xfs_lsn_t)0,
3909                               (XFS_LOG_FORCE | XFS_LOG_SYNC));
3910
3911                 xlog_recover_process_iunlinks(log);
3912
3913                 xlog_recover_check_summary(log);
3914
3915                 cmn_err(CE_NOTE,
3916                         "Ending XFS recovery on filesystem: %s (logdev: %s)",
3917                         log->l_mp->m_fsname, log->l_mp->m_logname ?
3918                         log->l_mp->m_logname : "internal");
3919                 log->l_flags &= ~XLOG_RECOVERY_NEEDED;
3920         } else {
3921                 cmn_err(CE_DEBUG,
3922                         "!Ending clean XFS mount for filesystem: %s\n",
3923                         log->l_mp->m_fsname);
3924         }
3925         return 0;
3926 }
3927
3928
3929 #if defined(DEBUG)
3930 /*
3931  * Read all of the agf and agi counters and check that they
3932  * are consistent with the superblock counters.
3933  */
3934 void
3935 xlog_recover_check_summary(
3936         xlog_t          *log)
3937 {
3938         xfs_mount_t     *mp;
3939         xfs_agf_t       *agfp;
3940         xfs_buf_t       *agfbp;
3941         xfs_buf_t       *agibp;
3942         xfs_buf_t       *sbbp;
3943 #ifdef XFS_LOUD_RECOVERY
3944         xfs_sb_t        *sbp;
3945 #endif
3946         xfs_agnumber_t  agno;
3947         __uint64_t      freeblks;
3948         __uint64_t      itotal;
3949         __uint64_t      ifree;
3950         int             error;
3951
3952         mp = log->l_mp;
3953
3954         freeblks = 0LL;
3955         itotal = 0LL;
3956         ifree = 0LL;
3957         for (agno = 0; agno < mp->m_sb.sb_agcount; agno++) {
3958                 error = xfs_read_agf(mp, NULL, agno, 0, &agfbp);
3959                 if (error) {
3960                         xfs_fs_cmn_err(CE_ALERT, mp,
3961                                         "xlog_recover_check_summary(agf)"
3962                                         "agf read failed agno %d error %d",
3963                                                         agno, error);
3964                 } else {
3965                         agfp = XFS_BUF_TO_AGF(agfbp);
3966                         freeblks += be32_to_cpu(agfp->agf_freeblks) +
3967                                     be32_to_cpu(agfp->agf_flcount);
3968                         xfs_buf_relse(agfbp);
3969                 }
3970
3971                 error = xfs_read_agi(mp, NULL, agno, &agibp);
3972                 if (!error) {
3973                         struct xfs_agi  *agi = XFS_BUF_TO_AGI(agibp);
3974
3975                         itotal += be32_to_cpu(agi->agi_count);
3976                         ifree += be32_to_cpu(agi->agi_freecount);
3977                         xfs_buf_relse(agibp);
3978                 }
3979         }
3980
3981         sbbp = xfs_getsb(mp, 0);
3982 #ifdef XFS_LOUD_RECOVERY
3983         sbp = &mp->m_sb;
3984         xfs_sb_from_disk(sbp, XFS_BUF_TO_SBP(sbbp));
3985         cmn_err(CE_NOTE,
3986                 "xlog_recover_check_summary: sb_icount %Lu itotal %Lu",
3987                 sbp->sb_icount, itotal);
3988         cmn_err(CE_NOTE,
3989                 "xlog_recover_check_summary: sb_ifree %Lu itotal %Lu",
3990                 sbp->sb_ifree, ifree);
3991         cmn_err(CE_NOTE,
3992                 "xlog_recover_check_summary: sb_fdblocks %Lu freeblks %Lu",
3993                 sbp->sb_fdblocks, freeblks);
3994 #if 0
3995         /*
3996          * This is turned off until I account for the allocation
3997          * btree blocks which live in free space.
3998          */
3999         ASSERT(sbp->sb_icount == itotal);
4000         ASSERT(sbp->sb_ifree == ifree);
4001         ASSERT(sbp->sb_fdblocks == freeblks);
4002 #endif
4003 #endif
4004         xfs_buf_relse(sbbp);
4005 }
4006 #endif /* DEBUG */