xfs: drop dmapi hooks
[sfrench/cifs-2.6.git] / fs / xfs / xfs_log.c
1 /*
2  * Copyright (c) 2000-2005 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_mount.h"
29 #include "xfs_error.h"
30 #include "xfs_log_priv.h"
31 #include "xfs_buf_item.h"
32 #include "xfs_bmap_btree.h"
33 #include "xfs_alloc_btree.h"
34 #include "xfs_ialloc_btree.h"
35 #include "xfs_log_recover.h"
36 #include "xfs_trans_priv.h"
37 #include "xfs_dir2_sf.h"
38 #include "xfs_attr_sf.h"
39 #include "xfs_dinode.h"
40 #include "xfs_inode.h"
41 #include "xfs_rw.h"
42 #include "xfs_trace.h"
43
44 kmem_zone_t     *xfs_log_ticket_zone;
45
46 /* Local miscellaneous function prototypes */
47 STATIC int       xlog_commit_record(struct log *log, struct xlog_ticket *ticket,
48                                     xlog_in_core_t **, xfs_lsn_t *);
49 STATIC xlog_t *  xlog_alloc_log(xfs_mount_t     *mp,
50                                 xfs_buftarg_t   *log_target,
51                                 xfs_daddr_t     blk_offset,
52                                 int             num_bblks);
53 STATIC int       xlog_space_left(xlog_t *log, int cycle, int bytes);
54 STATIC int       xlog_sync(xlog_t *log, xlog_in_core_t *iclog);
55 STATIC void      xlog_dealloc_log(xlog_t *log);
56
57 /* local state machine functions */
58 STATIC void xlog_state_done_syncing(xlog_in_core_t *iclog, int);
59 STATIC void xlog_state_do_callback(xlog_t *log,int aborted, xlog_in_core_t *iclog);
60 STATIC int  xlog_state_get_iclog_space(xlog_t           *log,
61                                        int              len,
62                                        xlog_in_core_t   **iclog,
63                                        xlog_ticket_t    *ticket,
64                                        int              *continued_write,
65                                        int              *logoffsetp);
66 STATIC int  xlog_state_release_iclog(xlog_t             *log,
67                                      xlog_in_core_t     *iclog);
68 STATIC void xlog_state_switch_iclogs(xlog_t             *log,
69                                      xlog_in_core_t *iclog,
70                                      int                eventual_size);
71 STATIC void xlog_state_want_sync(xlog_t *log, xlog_in_core_t *iclog);
72
73 /* local functions to manipulate grant head */
74 STATIC int  xlog_grant_log_space(xlog_t         *log,
75                                  xlog_ticket_t  *xtic);
76 STATIC void xlog_grant_push_ail(xfs_mount_t     *mp,
77                                 int             need_bytes);
78 STATIC void xlog_regrant_reserve_log_space(xlog_t        *log,
79                                            xlog_ticket_t *ticket);
80 STATIC int xlog_regrant_write_log_space(xlog_t          *log,
81                                          xlog_ticket_t  *ticket);
82 STATIC void xlog_ungrant_log_space(xlog_t        *log,
83                                    xlog_ticket_t *ticket);
84
85 #if defined(DEBUG)
86 STATIC void     xlog_verify_dest_ptr(xlog_t *log, char *ptr);
87 STATIC void     xlog_verify_grant_head(xlog_t *log, int equals);
88 STATIC void     xlog_verify_iclog(xlog_t *log, xlog_in_core_t *iclog,
89                                   int count, boolean_t syncing);
90 STATIC void     xlog_verify_tail_lsn(xlog_t *log, xlog_in_core_t *iclog,
91                                      xfs_lsn_t tail_lsn);
92 #else
93 #define xlog_verify_dest_ptr(a,b)
94 #define xlog_verify_grant_head(a,b)
95 #define xlog_verify_iclog(a,b,c,d)
96 #define xlog_verify_tail_lsn(a,b,c)
97 #endif
98
99 STATIC int      xlog_iclogs_empty(xlog_t *log);
100
101
102 static void
103 xlog_ins_ticketq(struct xlog_ticket **qp, struct xlog_ticket *tic)
104 {
105         if (*qp) {
106                 tic->t_next         = (*qp);
107                 tic->t_prev         = (*qp)->t_prev;
108                 (*qp)->t_prev->t_next = tic;
109                 (*qp)->t_prev       = tic;
110         } else {
111                 tic->t_prev = tic->t_next = tic;
112                 *qp = tic;
113         }
114
115         tic->t_flags |= XLOG_TIC_IN_Q;
116 }
117
118 static void
119 xlog_del_ticketq(struct xlog_ticket **qp, struct xlog_ticket *tic)
120 {
121         if (tic == tic->t_next) {
122                 *qp = NULL;
123         } else {
124                 *qp = tic->t_next;
125                 tic->t_next->t_prev = tic->t_prev;
126                 tic->t_prev->t_next = tic->t_next;
127         }
128
129         tic->t_next = tic->t_prev = NULL;
130         tic->t_flags &= ~XLOG_TIC_IN_Q;
131 }
132
133 static void
134 xlog_grant_sub_space(struct log *log, int bytes)
135 {
136         log->l_grant_write_bytes -= bytes;
137         if (log->l_grant_write_bytes < 0) {
138                 log->l_grant_write_bytes += log->l_logsize;
139                 log->l_grant_write_cycle--;
140         }
141
142         log->l_grant_reserve_bytes -= bytes;
143         if ((log)->l_grant_reserve_bytes < 0) {
144                 log->l_grant_reserve_bytes += log->l_logsize;
145                 log->l_grant_reserve_cycle--;
146         }
147
148 }
149
150 static void
151 xlog_grant_add_space_write(struct log *log, int bytes)
152 {
153         int tmp = log->l_logsize - log->l_grant_write_bytes;
154         if (tmp > bytes)
155                 log->l_grant_write_bytes += bytes;
156         else {
157                 log->l_grant_write_cycle++;
158                 log->l_grant_write_bytes = bytes - tmp;
159         }
160 }
161
162 static void
163 xlog_grant_add_space_reserve(struct log *log, int bytes)
164 {
165         int tmp = log->l_logsize - log->l_grant_reserve_bytes;
166         if (tmp > bytes)
167                 log->l_grant_reserve_bytes += bytes;
168         else {
169                 log->l_grant_reserve_cycle++;
170                 log->l_grant_reserve_bytes = bytes - tmp;
171         }
172 }
173
174 static inline void
175 xlog_grant_add_space(struct log *log, int bytes)
176 {
177         xlog_grant_add_space_write(log, bytes);
178         xlog_grant_add_space_reserve(log, bytes);
179 }
180
181 static void
182 xlog_tic_reset_res(xlog_ticket_t *tic)
183 {
184         tic->t_res_num = 0;
185         tic->t_res_arr_sum = 0;
186         tic->t_res_num_ophdrs = 0;
187 }
188
189 static void
190 xlog_tic_add_region(xlog_ticket_t *tic, uint len, uint type)
191 {
192         if (tic->t_res_num == XLOG_TIC_LEN_MAX) {
193                 /* add to overflow and start again */
194                 tic->t_res_o_flow += tic->t_res_arr_sum;
195                 tic->t_res_num = 0;
196                 tic->t_res_arr_sum = 0;
197         }
198
199         tic->t_res_arr[tic->t_res_num].r_len = len;
200         tic->t_res_arr[tic->t_res_num].r_type = type;
201         tic->t_res_arr_sum += len;
202         tic->t_res_num++;
203 }
204
205 /*
206  * NOTES:
207  *
208  *      1. currblock field gets updated at startup and after in-core logs
209  *              marked as with WANT_SYNC.
210  */
211
212 /*
213  * This routine is called when a user of a log manager ticket is done with
214  * the reservation.  If the ticket was ever used, then a commit record for
215  * the associated transaction is written out as a log operation header with
216  * no data.  The flag XLOG_TIC_INITED is set when the first write occurs with
217  * a given ticket.  If the ticket was one with a permanent reservation, then
218  * a few operations are done differently.  Permanent reservation tickets by
219  * default don't release the reservation.  They just commit the current
220  * transaction with the belief that the reservation is still needed.  A flag
221  * must be passed in before permanent reservations are actually released.
222  * When these type of tickets are not released, they need to be set into
223  * the inited state again.  By doing this, a start record will be written
224  * out when the next write occurs.
225  */
226 xfs_lsn_t
227 xfs_log_done(
228         struct xfs_mount        *mp,
229         struct xlog_ticket      *ticket,
230         struct xlog_in_core     **iclog,
231         uint                    flags)
232 {
233         struct log              *log = mp->m_log;
234         xfs_lsn_t               lsn = 0;
235
236         if (XLOG_FORCED_SHUTDOWN(log) ||
237             /*
238              * If nothing was ever written, don't write out commit record.
239              * If we get an error, just continue and give back the log ticket.
240              */
241             (((ticket->t_flags & XLOG_TIC_INITED) == 0) &&
242              (xlog_commit_record(log, ticket, iclog, &lsn)))) {
243                 lsn = (xfs_lsn_t) -1;
244                 if (ticket->t_flags & XLOG_TIC_PERM_RESERV) {
245                         flags |= XFS_LOG_REL_PERM_RESERV;
246                 }
247         }
248
249
250         if ((ticket->t_flags & XLOG_TIC_PERM_RESERV) == 0 ||
251             (flags & XFS_LOG_REL_PERM_RESERV)) {
252                 trace_xfs_log_done_nonperm(log, ticket);
253
254                 /*
255                  * Release ticket if not permanent reservation or a specific
256                  * request has been made to release a permanent reservation.
257                  */
258                 xlog_ungrant_log_space(log, ticket);
259                 xfs_log_ticket_put(ticket);
260         } else {
261                 trace_xfs_log_done_perm(log, ticket);
262
263                 xlog_regrant_reserve_log_space(log, ticket);
264                 /* If this ticket was a permanent reservation and we aren't
265                  * trying to release it, reset the inited flags; so next time
266                  * we write, a start record will be written out.
267                  */
268                 ticket->t_flags |= XLOG_TIC_INITED;
269         }
270
271         return lsn;
272 }
273
274 /*
275  * Attaches a new iclog I/O completion callback routine during
276  * transaction commit.  If the log is in error state, a non-zero
277  * return code is handed back and the caller is responsible for
278  * executing the callback at an appropriate time.
279  */
280 int
281 xfs_log_notify(
282         struct xfs_mount        *mp,
283         struct xlog_in_core     *iclog,
284         xfs_log_callback_t      *cb)
285 {
286         int     abortflg;
287
288         spin_lock(&iclog->ic_callback_lock);
289         abortflg = (iclog->ic_state & XLOG_STATE_IOERROR);
290         if (!abortflg) {
291                 ASSERT_ALWAYS((iclog->ic_state == XLOG_STATE_ACTIVE) ||
292                               (iclog->ic_state == XLOG_STATE_WANT_SYNC));
293                 cb->cb_next = NULL;
294                 *(iclog->ic_callback_tail) = cb;
295                 iclog->ic_callback_tail = &(cb->cb_next);
296         }
297         spin_unlock(&iclog->ic_callback_lock);
298         return abortflg;
299 }
300
301 int
302 xfs_log_release_iclog(
303         struct xfs_mount        *mp,
304         struct xlog_in_core     *iclog)
305 {
306         if (xlog_state_release_iclog(mp->m_log, iclog)) {
307                 xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR);
308                 return EIO;
309         }
310
311         return 0;
312 }
313
314 /*
315  *  1. Reserve an amount of on-disk log space and return a ticket corresponding
316  *      to the reservation.
317  *  2. Potentially, push buffers at tail of log to disk.
318  *
319  * Each reservation is going to reserve extra space for a log record header.
320  * When writes happen to the on-disk log, we don't subtract the length of the
321  * log record header from any reservation.  By wasting space in each
322  * reservation, we prevent over allocation problems.
323  */
324 int
325 xfs_log_reserve(
326         struct xfs_mount        *mp,
327         int                     unit_bytes,
328         int                     cnt,
329         struct xlog_ticket      **ticket,
330         __uint8_t               client,
331         uint                    flags,
332         uint                    t_type)
333 {
334         struct log              *log = mp->m_log;
335         struct xlog_ticket      *internal_ticket;
336         int                     retval = 0;
337
338         ASSERT(client == XFS_TRANSACTION || client == XFS_LOG);
339         ASSERT((flags & XFS_LOG_NOSLEEP) == 0);
340
341         if (XLOG_FORCED_SHUTDOWN(log))
342                 return XFS_ERROR(EIO);
343
344         XFS_STATS_INC(xs_try_logspace);
345
346
347         if (*ticket != NULL) {
348                 ASSERT(flags & XFS_LOG_PERM_RESERV);
349                 internal_ticket = *ticket;
350
351                 /*
352                  * this is a new transaction on the ticket, so we need to
353                  * change the transaction ID so that the next transaction has a
354                  * different TID in the log. Just add one to the existing tid
355                  * so that we can see chains of rolling transactions in the log
356                  * easily.
357                  */
358                 internal_ticket->t_tid++;
359
360                 trace_xfs_log_reserve(log, internal_ticket);
361
362                 xlog_grant_push_ail(mp, internal_ticket->t_unit_res);
363                 retval = xlog_regrant_write_log_space(log, internal_ticket);
364         } else {
365                 /* may sleep if need to allocate more tickets */
366                 internal_ticket = xlog_ticket_alloc(log, unit_bytes, cnt,
367                                                   client, flags,
368                                                   KM_SLEEP|KM_MAYFAIL);
369                 if (!internal_ticket)
370                         return XFS_ERROR(ENOMEM);
371                 internal_ticket->t_trans_type = t_type;
372                 *ticket = internal_ticket;
373
374                 trace_xfs_log_reserve(log, internal_ticket);
375
376                 xlog_grant_push_ail(mp,
377                                     (internal_ticket->t_unit_res *
378                                      internal_ticket->t_cnt));
379                 retval = xlog_grant_log_space(log, internal_ticket);
380         }
381
382         return retval;
383 }       /* xfs_log_reserve */
384
385
386 /*
387  * Mount a log filesystem
388  *
389  * mp           - ubiquitous xfs mount point structure
390  * log_target   - buftarg of on-disk log device
391  * blk_offset   - Start block # where block size is 512 bytes (BBSIZE)
392  * num_bblocks  - Number of BBSIZE blocks in on-disk log
393  *
394  * Return error or zero.
395  */
396 int
397 xfs_log_mount(
398         xfs_mount_t     *mp,
399         xfs_buftarg_t   *log_target,
400         xfs_daddr_t     blk_offset,
401         int             num_bblks)
402 {
403         int             error;
404
405         if (!(mp->m_flags & XFS_MOUNT_NORECOVERY))
406                 cmn_err(CE_NOTE, "XFS mounting filesystem %s", mp->m_fsname);
407         else {
408                 cmn_err(CE_NOTE,
409                         "!Mounting filesystem \"%s\" in no-recovery mode.  Filesystem will be inconsistent.",
410                         mp->m_fsname);
411                 ASSERT(mp->m_flags & XFS_MOUNT_RDONLY);
412         }
413
414         mp->m_log = xlog_alloc_log(mp, log_target, blk_offset, num_bblks);
415         if (IS_ERR(mp->m_log)) {
416                 error = -PTR_ERR(mp->m_log);
417                 goto out;
418         }
419
420         /*
421          * Initialize the AIL now we have a log.
422          */
423         error = xfs_trans_ail_init(mp);
424         if (error) {
425                 cmn_err(CE_WARN, "XFS: AIL initialisation failed: error %d", error);
426                 goto out_free_log;
427         }
428         mp->m_log->l_ailp = mp->m_ail;
429
430         /*
431          * skip log recovery on a norecovery mount.  pretend it all
432          * just worked.
433          */
434         if (!(mp->m_flags & XFS_MOUNT_NORECOVERY)) {
435                 int     readonly = (mp->m_flags & XFS_MOUNT_RDONLY);
436
437                 if (readonly)
438                         mp->m_flags &= ~XFS_MOUNT_RDONLY;
439
440                 error = xlog_recover(mp->m_log);
441
442                 if (readonly)
443                         mp->m_flags |= XFS_MOUNT_RDONLY;
444                 if (error) {
445                         cmn_err(CE_WARN, "XFS: log mount/recovery failed: error %d", error);
446                         goto out_destroy_ail;
447                 }
448         }
449
450         /* Normal transactions can now occur */
451         mp->m_log->l_flags &= ~XLOG_ACTIVE_RECOVERY;
452
453         /*
454          * Now the log has been fully initialised and we know were our
455          * space grant counters are, we can initialise the permanent ticket
456          * needed for delayed logging to work.
457          */
458         xlog_cil_init_post_recovery(mp->m_log);
459
460         return 0;
461
462 out_destroy_ail:
463         xfs_trans_ail_destroy(mp);
464 out_free_log:
465         xlog_dealloc_log(mp->m_log);
466 out:
467         return error;
468 }
469
470 /*
471  * Finish the recovery of the file system.  This is separate from
472  * the xfs_log_mount() call, because it depends on the code in
473  * xfs_mountfs() to read in the root and real-time bitmap inodes
474  * between calling xfs_log_mount() and here.
475  *
476  * mp           - ubiquitous xfs mount point structure
477  */
478 int
479 xfs_log_mount_finish(xfs_mount_t *mp)
480 {
481         int     error;
482
483         if (!(mp->m_flags & XFS_MOUNT_NORECOVERY))
484                 error = xlog_recover_finish(mp->m_log);
485         else {
486                 error = 0;
487                 ASSERT(mp->m_flags & XFS_MOUNT_RDONLY);
488         }
489
490         return error;
491 }
492
493 /*
494  * Final log writes as part of unmount.
495  *
496  * Mark the filesystem clean as unmount happens.  Note that during relocation
497  * this routine needs to be executed as part of source-bag while the
498  * deallocation must not be done until source-end.
499  */
500
501 /*
502  * Unmount record used to have a string "Unmount filesystem--" in the
503  * data section where the "Un" was really a magic number (XLOG_UNMOUNT_TYPE).
504  * We just write the magic number now since that particular field isn't
505  * currently architecture converted and "nUmount" is a bit foo.
506  * As far as I know, there weren't any dependencies on the old behaviour.
507  */
508
509 int
510 xfs_log_unmount_write(xfs_mount_t *mp)
511 {
512         xlog_t           *log = mp->m_log;
513         xlog_in_core_t   *iclog;
514 #ifdef DEBUG
515         xlog_in_core_t   *first_iclog;
516 #endif
517         xlog_ticket_t   *tic = NULL;
518         xfs_lsn_t        lsn;
519         int              error;
520
521         /*
522          * Don't write out unmount record on read-only mounts.
523          * Or, if we are doing a forced umount (typically because of IO errors).
524          */
525         if (mp->m_flags & XFS_MOUNT_RDONLY)
526                 return 0;
527
528         error = _xfs_log_force(mp, XFS_LOG_SYNC, NULL);
529         ASSERT(error || !(XLOG_FORCED_SHUTDOWN(log)));
530
531 #ifdef DEBUG
532         first_iclog = iclog = log->l_iclog;
533         do {
534                 if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
535                         ASSERT(iclog->ic_state & XLOG_STATE_ACTIVE);
536                         ASSERT(iclog->ic_offset == 0);
537                 }
538                 iclog = iclog->ic_next;
539         } while (iclog != first_iclog);
540 #endif
541         if (! (XLOG_FORCED_SHUTDOWN(log))) {
542                 error = xfs_log_reserve(mp, 600, 1, &tic,
543                                         XFS_LOG, 0, XLOG_UNMOUNT_REC_TYPE);
544                 if (!error) {
545                         /* the data section must be 32 bit size aligned */
546                         struct {
547                             __uint16_t magic;
548                             __uint16_t pad1;
549                             __uint32_t pad2; /* may as well make it 64 bits */
550                         } magic = {
551                                 .magic = XLOG_UNMOUNT_TYPE,
552                         };
553                         struct xfs_log_iovec reg = {
554                                 .i_addr = (void *)&magic,
555                                 .i_len = sizeof(magic),
556                                 .i_type = XLOG_REG_TYPE_UNMOUNT,
557                         };
558                         struct xfs_log_vec vec = {
559                                 .lv_niovecs = 1,
560                                 .lv_iovecp = &reg,
561                         };
562
563                         /* remove inited flag */
564                         tic->t_flags = 0;
565                         error = xlog_write(log, &vec, tic, &lsn,
566                                            NULL, XLOG_UNMOUNT_TRANS);
567                         /*
568                          * At this point, we're umounting anyway,
569                          * so there's no point in transitioning log state
570                          * to IOERROR. Just continue...
571                          */
572                 }
573
574                 if (error) {
575                         xfs_fs_cmn_err(CE_ALERT, mp,
576                                 "xfs_log_unmount: unmount record failed");
577                 }
578
579
580                 spin_lock(&log->l_icloglock);
581                 iclog = log->l_iclog;
582                 atomic_inc(&iclog->ic_refcnt);
583                 xlog_state_want_sync(log, iclog);
584                 spin_unlock(&log->l_icloglock);
585                 error = xlog_state_release_iclog(log, iclog);
586
587                 spin_lock(&log->l_icloglock);
588                 if (!(iclog->ic_state == XLOG_STATE_ACTIVE ||
589                       iclog->ic_state == XLOG_STATE_DIRTY)) {
590                         if (!XLOG_FORCED_SHUTDOWN(log)) {
591                                 sv_wait(&iclog->ic_force_wait, PMEM,
592                                         &log->l_icloglock, s);
593                         } else {
594                                 spin_unlock(&log->l_icloglock);
595                         }
596                 } else {
597                         spin_unlock(&log->l_icloglock);
598                 }
599                 if (tic) {
600                         trace_xfs_log_umount_write(log, tic);
601                         xlog_ungrant_log_space(log, tic);
602                         xfs_log_ticket_put(tic);
603                 }
604         } else {
605                 /*
606                  * We're already in forced_shutdown mode, couldn't
607                  * even attempt to write out the unmount transaction.
608                  *
609                  * Go through the motions of sync'ing and releasing
610                  * the iclog, even though no I/O will actually happen,
611                  * we need to wait for other log I/Os that may already
612                  * be in progress.  Do this as a separate section of
613                  * code so we'll know if we ever get stuck here that
614                  * we're in this odd situation of trying to unmount
615                  * a file system that went into forced_shutdown as
616                  * the result of an unmount..
617                  */
618                 spin_lock(&log->l_icloglock);
619                 iclog = log->l_iclog;
620                 atomic_inc(&iclog->ic_refcnt);
621
622                 xlog_state_want_sync(log, iclog);
623                 spin_unlock(&log->l_icloglock);
624                 error =  xlog_state_release_iclog(log, iclog);
625
626                 spin_lock(&log->l_icloglock);
627
628                 if ( ! (   iclog->ic_state == XLOG_STATE_ACTIVE
629                         || iclog->ic_state == XLOG_STATE_DIRTY
630                         || iclog->ic_state == XLOG_STATE_IOERROR) ) {
631
632                                 sv_wait(&iclog->ic_force_wait, PMEM,
633                                         &log->l_icloglock, s);
634                 } else {
635                         spin_unlock(&log->l_icloglock);
636                 }
637         }
638
639         return error;
640 }       /* xfs_log_unmount_write */
641
642 /*
643  * Deallocate log structures for unmount/relocation.
644  *
645  * We need to stop the aild from running before we destroy
646  * and deallocate the log as the aild references the log.
647  */
648 void
649 xfs_log_unmount(xfs_mount_t *mp)
650 {
651         xfs_trans_ail_destroy(mp);
652         xlog_dealloc_log(mp->m_log);
653 }
654
655 void
656 xfs_log_item_init(
657         struct xfs_mount        *mp,
658         struct xfs_log_item     *item,
659         int                     type,
660         struct xfs_item_ops     *ops)
661 {
662         item->li_mountp = mp;
663         item->li_ailp = mp->m_ail;
664         item->li_type = type;
665         item->li_ops = ops;
666         item->li_lv = NULL;
667
668         INIT_LIST_HEAD(&item->li_ail);
669         INIT_LIST_HEAD(&item->li_cil);
670 }
671
672 /*
673  * Write region vectors to log.  The write happens using the space reservation
674  * of the ticket (tic).  It is not a requirement that all writes for a given
675  * transaction occur with one call to xfs_log_write(). However, it is important
676  * to note that the transaction reservation code makes an assumption about the
677  * number of log headers a transaction requires that may be violated if you
678  * don't pass all the transaction vectors in one call....
679  */
680 int
681 xfs_log_write(
682         struct xfs_mount        *mp,
683         struct xfs_log_iovec    reg[],
684         int                     nentries,
685         struct xlog_ticket      *tic,
686         xfs_lsn_t               *start_lsn)
687 {
688         struct log              *log = mp->m_log;
689         int                     error;
690         struct xfs_log_vec      vec = {
691                 .lv_niovecs = nentries,
692                 .lv_iovecp = reg,
693         };
694
695         if (XLOG_FORCED_SHUTDOWN(log))
696                 return XFS_ERROR(EIO);
697
698         error = xlog_write(log, &vec, tic, start_lsn, NULL, 0);
699         if (error)
700                 xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR);
701         return error;
702 }
703
704 void
705 xfs_log_move_tail(xfs_mount_t   *mp,
706                   xfs_lsn_t     tail_lsn)
707 {
708         xlog_ticket_t   *tic;
709         xlog_t          *log = mp->m_log;
710         int             need_bytes, free_bytes, cycle, bytes;
711
712         if (XLOG_FORCED_SHUTDOWN(log))
713                 return;
714
715         if (tail_lsn == 0) {
716                 /* needed since sync_lsn is 64 bits */
717                 spin_lock(&log->l_icloglock);
718                 tail_lsn = log->l_last_sync_lsn;
719                 spin_unlock(&log->l_icloglock);
720         }
721
722         spin_lock(&log->l_grant_lock);
723
724         /* Also an invalid lsn.  1 implies that we aren't passing in a valid
725          * tail_lsn.
726          */
727         if (tail_lsn != 1) {
728                 log->l_tail_lsn = tail_lsn;
729         }
730
731         if ((tic = log->l_write_headq)) {
732 #ifdef DEBUG
733                 if (log->l_flags & XLOG_ACTIVE_RECOVERY)
734                         panic("Recovery problem");
735 #endif
736                 cycle = log->l_grant_write_cycle;
737                 bytes = log->l_grant_write_bytes;
738                 free_bytes = xlog_space_left(log, cycle, bytes);
739                 do {
740                         ASSERT(tic->t_flags & XLOG_TIC_PERM_RESERV);
741
742                         if (free_bytes < tic->t_unit_res && tail_lsn != 1)
743                                 break;
744                         tail_lsn = 0;
745                         free_bytes -= tic->t_unit_res;
746                         sv_signal(&tic->t_wait);
747                         tic = tic->t_next;
748                 } while (tic != log->l_write_headq);
749         }
750         if ((tic = log->l_reserve_headq)) {
751 #ifdef DEBUG
752                 if (log->l_flags & XLOG_ACTIVE_RECOVERY)
753                         panic("Recovery problem");
754 #endif
755                 cycle = log->l_grant_reserve_cycle;
756                 bytes = log->l_grant_reserve_bytes;
757                 free_bytes = xlog_space_left(log, cycle, bytes);
758                 do {
759                         if (tic->t_flags & XLOG_TIC_PERM_RESERV)
760                                 need_bytes = tic->t_unit_res*tic->t_cnt;
761                         else
762                                 need_bytes = tic->t_unit_res;
763                         if (free_bytes < need_bytes && tail_lsn != 1)
764                                 break;
765                         tail_lsn = 0;
766                         free_bytes -= need_bytes;
767                         sv_signal(&tic->t_wait);
768                         tic = tic->t_next;
769                 } while (tic != log->l_reserve_headq);
770         }
771         spin_unlock(&log->l_grant_lock);
772 }       /* xfs_log_move_tail */
773
774 /*
775  * Determine if we have a transaction that has gone to disk
776  * that needs to be covered. To begin the transition to the idle state
777  * firstly the log needs to be idle (no AIL and nothing in the iclogs).
778  * If we are then in a state where covering is needed, the caller is informed
779  * that dummy transactions are required to move the log into the idle state.
780  *
781  * Because this is called as part of the sync process, we should also indicate
782  * that dummy transactions should be issued in anything but the covered or
783  * idle states. This ensures that the log tail is accurately reflected in
784  * the log at the end of the sync, hence if a crash occurrs avoids replay
785  * of transactions where the metadata is already on disk.
786  */
787 int
788 xfs_log_need_covered(xfs_mount_t *mp)
789 {
790         int             needed = 0;
791         xlog_t          *log = mp->m_log;
792
793         if (!xfs_fs_writable(mp))
794                 return 0;
795
796         spin_lock(&log->l_icloglock);
797         switch (log->l_covered_state) {
798         case XLOG_STATE_COVER_DONE:
799         case XLOG_STATE_COVER_DONE2:
800         case XLOG_STATE_COVER_IDLE:
801                 break;
802         case XLOG_STATE_COVER_NEED:
803         case XLOG_STATE_COVER_NEED2:
804                 if (!xfs_trans_ail_tail(log->l_ailp) &&
805                     xlog_iclogs_empty(log)) {
806                         if (log->l_covered_state == XLOG_STATE_COVER_NEED)
807                                 log->l_covered_state = XLOG_STATE_COVER_DONE;
808                         else
809                                 log->l_covered_state = XLOG_STATE_COVER_DONE2;
810                 }
811                 /* FALLTHRU */
812         default:
813                 needed = 1;
814                 break;
815         }
816         spin_unlock(&log->l_icloglock);
817         return needed;
818 }
819
820 /******************************************************************************
821  *
822  *      local routines
823  *
824  ******************************************************************************
825  */
826
827 /* xfs_trans_tail_ail returns 0 when there is nothing in the list.
828  * The log manager must keep track of the last LR which was committed
829  * to disk.  The lsn of this LR will become the new tail_lsn whenever
830  * xfs_trans_tail_ail returns 0.  If we don't do this, we run into
831  * the situation where stuff could be written into the log but nothing
832  * was ever in the AIL when asked.  Eventually, we panic since the
833  * tail hits the head.
834  *
835  * We may be holding the log iclog lock upon entering this routine.
836  */
837 xfs_lsn_t
838 xlog_assign_tail_lsn(xfs_mount_t *mp)
839 {
840         xfs_lsn_t tail_lsn;
841         xlog_t    *log = mp->m_log;
842
843         tail_lsn = xfs_trans_ail_tail(mp->m_ail);
844         spin_lock(&log->l_grant_lock);
845         if (tail_lsn != 0) {
846                 log->l_tail_lsn = tail_lsn;
847         } else {
848                 tail_lsn = log->l_tail_lsn = log->l_last_sync_lsn;
849         }
850         spin_unlock(&log->l_grant_lock);
851
852         return tail_lsn;
853 }       /* xlog_assign_tail_lsn */
854
855
856 /*
857  * Return the space in the log between the tail and the head.  The head
858  * is passed in the cycle/bytes formal parms.  In the special case where
859  * the reserve head has wrapped passed the tail, this calculation is no
860  * longer valid.  In this case, just return 0 which means there is no space
861  * in the log.  This works for all places where this function is called
862  * with the reserve head.  Of course, if the write head were to ever
863  * wrap the tail, we should blow up.  Rather than catch this case here,
864  * we depend on other ASSERTions in other parts of the code.   XXXmiken
865  *
866  * This code also handles the case where the reservation head is behind
867  * the tail.  The details of this case are described below, but the end
868  * result is that we return the size of the log as the amount of space left.
869  */
870 STATIC int
871 xlog_space_left(xlog_t *log, int cycle, int bytes)
872 {
873         int free_bytes;
874         int tail_bytes;
875         int tail_cycle;
876
877         tail_bytes = BBTOB(BLOCK_LSN(log->l_tail_lsn));
878         tail_cycle = CYCLE_LSN(log->l_tail_lsn);
879         if ((tail_cycle == cycle) && (bytes >= tail_bytes)) {
880                 free_bytes = log->l_logsize - (bytes - tail_bytes);
881         } else if ((tail_cycle + 1) < cycle) {
882                 return 0;
883         } else if (tail_cycle < cycle) {
884                 ASSERT(tail_cycle == (cycle - 1));
885                 free_bytes = tail_bytes - bytes;
886         } else {
887                 /*
888                  * The reservation head is behind the tail.
889                  * In this case we just want to return the size of the
890                  * log as the amount of space left.
891                  */
892                 xfs_fs_cmn_err(CE_ALERT, log->l_mp,
893                         "xlog_space_left: head behind tail\n"
894                         "  tail_cycle = %d, tail_bytes = %d\n"
895                         "  GH   cycle = %d, GH   bytes = %d",
896                         tail_cycle, tail_bytes, cycle, bytes);
897                 ASSERT(0);
898                 free_bytes = log->l_logsize;
899         }
900         return free_bytes;
901 }       /* xlog_space_left */
902
903
904 /*
905  * Log function which is called when an io completes.
906  *
907  * The log manager needs its own routine, in order to control what
908  * happens with the buffer after the write completes.
909  */
910 void
911 xlog_iodone(xfs_buf_t *bp)
912 {
913         xlog_in_core_t  *iclog;
914         xlog_t          *l;
915         int             aborted;
916
917         iclog = XFS_BUF_FSPRIVATE(bp, xlog_in_core_t *);
918         ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) == (unsigned long) 2);
919         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
920         aborted = 0;
921         l = iclog->ic_log;
922
923         /*
924          * If the _XFS_BARRIER_FAILED flag was set by a lower
925          * layer, it means the underlying device no longer supports
926          * barrier I/O. Warn loudly and turn off barriers.
927          */
928         if (bp->b_flags & _XFS_BARRIER_FAILED) {
929                 bp->b_flags &= ~_XFS_BARRIER_FAILED;
930                 l->l_mp->m_flags &= ~XFS_MOUNT_BARRIER;
931                 xfs_fs_cmn_err(CE_WARN, l->l_mp,
932                                 "xlog_iodone: Barriers are no longer supported"
933                                 " by device. Disabling barriers\n");
934         }
935
936         /*
937          * Race to shutdown the filesystem if we see an error.
938          */
939         if (XFS_TEST_ERROR((XFS_BUF_GETERROR(bp)), l->l_mp,
940                         XFS_ERRTAG_IODONE_IOERR, XFS_RANDOM_IODONE_IOERR)) {
941                 xfs_ioerror_alert("xlog_iodone", l->l_mp, bp, XFS_BUF_ADDR(bp));
942                 XFS_BUF_STALE(bp);
943                 xfs_force_shutdown(l->l_mp, SHUTDOWN_LOG_IO_ERROR);
944                 /*
945                  * This flag will be propagated to the trans-committed
946                  * callback routines to let them know that the log-commit
947                  * didn't succeed.
948                  */
949                 aborted = XFS_LI_ABORTED;
950         } else if (iclog->ic_state & XLOG_STATE_IOERROR) {
951                 aborted = XFS_LI_ABORTED;
952         }
953
954         /* log I/O is always issued ASYNC */
955         ASSERT(XFS_BUF_ISASYNC(bp));
956         xlog_state_done_syncing(iclog, aborted);
957         /*
958          * do not reference the buffer (bp) here as we could race
959          * with it being freed after writing the unmount record to the
960          * log.
961          */
962
963 }       /* xlog_iodone */
964
965 /*
966  * Return size of each in-core log record buffer.
967  *
968  * All machines get 8 x 32kB buffers by default, unless tuned otherwise.
969  *
970  * If the filesystem blocksize is too large, we may need to choose a
971  * larger size since the directory code currently logs entire blocks.
972  */
973
974 STATIC void
975 xlog_get_iclog_buffer_size(xfs_mount_t  *mp,
976                            xlog_t       *log)
977 {
978         int size;
979         int xhdrs;
980
981         if (mp->m_logbufs <= 0)
982                 log->l_iclog_bufs = XLOG_MAX_ICLOGS;
983         else
984                 log->l_iclog_bufs = mp->m_logbufs;
985
986         /*
987          * Buffer size passed in from mount system call.
988          */
989         if (mp->m_logbsize > 0) {
990                 size = log->l_iclog_size = mp->m_logbsize;
991                 log->l_iclog_size_log = 0;
992                 while (size != 1) {
993                         log->l_iclog_size_log++;
994                         size >>= 1;
995                 }
996
997                 if (xfs_sb_version_haslogv2(&mp->m_sb)) {
998                         /* # headers = size / 32k
999                          * one header holds cycles from 32k of data
1000                          */
1001
1002                         xhdrs = mp->m_logbsize / XLOG_HEADER_CYCLE_SIZE;
1003                         if (mp->m_logbsize % XLOG_HEADER_CYCLE_SIZE)
1004                                 xhdrs++;
1005                         log->l_iclog_hsize = xhdrs << BBSHIFT;
1006                         log->l_iclog_heads = xhdrs;
1007                 } else {
1008                         ASSERT(mp->m_logbsize <= XLOG_BIG_RECORD_BSIZE);
1009                         log->l_iclog_hsize = BBSIZE;
1010                         log->l_iclog_heads = 1;
1011                 }
1012                 goto done;
1013         }
1014
1015         /* All machines use 32kB buffers by default. */
1016         log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;
1017         log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
1018
1019         /* the default log size is 16k or 32k which is one header sector */
1020         log->l_iclog_hsize = BBSIZE;
1021         log->l_iclog_heads = 1;
1022
1023 done:
1024         /* are we being asked to make the sizes selected above visible? */
1025         if (mp->m_logbufs == 0)
1026                 mp->m_logbufs = log->l_iclog_bufs;
1027         if (mp->m_logbsize == 0)
1028                 mp->m_logbsize = log->l_iclog_size;
1029 }       /* xlog_get_iclog_buffer_size */
1030
1031
1032 /*
1033  * This routine initializes some of the log structure for a given mount point.
1034  * Its primary purpose is to fill in enough, so recovery can occur.  However,
1035  * some other stuff may be filled in too.
1036  */
1037 STATIC xlog_t *
1038 xlog_alloc_log(xfs_mount_t      *mp,
1039                xfs_buftarg_t    *log_target,
1040                xfs_daddr_t      blk_offset,
1041                int              num_bblks)
1042 {
1043         xlog_t                  *log;
1044         xlog_rec_header_t       *head;
1045         xlog_in_core_t          **iclogp;
1046         xlog_in_core_t          *iclog, *prev_iclog=NULL;
1047         xfs_buf_t               *bp;
1048         int                     i;
1049         int                     iclogsize;
1050         int                     error = ENOMEM;
1051         uint                    log2_size = 0;
1052
1053         log = kmem_zalloc(sizeof(xlog_t), KM_MAYFAIL);
1054         if (!log) {
1055                 xlog_warn("XFS: Log allocation failed: No memory!");
1056                 goto out;
1057         }
1058
1059         log->l_mp          = mp;
1060         log->l_targ        = log_target;
1061         log->l_logsize     = BBTOB(num_bblks);
1062         log->l_logBBstart  = blk_offset;
1063         log->l_logBBsize   = num_bblks;
1064         log->l_covered_state = XLOG_STATE_COVER_IDLE;
1065         log->l_flags       |= XLOG_ACTIVE_RECOVERY;
1066
1067         log->l_prev_block  = -1;
1068         log->l_tail_lsn    = xlog_assign_lsn(1, 0);
1069         /* log->l_tail_lsn = 0x100000000LL; cycle = 1; current block = 0 */
1070         log->l_last_sync_lsn = log->l_tail_lsn;
1071         log->l_curr_cycle  = 1;     /* 0 is bad since this is initial value */
1072         log->l_grant_reserve_cycle = 1;
1073         log->l_grant_write_cycle = 1;
1074
1075         error = EFSCORRUPTED;
1076         if (xfs_sb_version_hassector(&mp->m_sb)) {
1077                 log2_size = mp->m_sb.sb_logsectlog;
1078                 if (log2_size < BBSHIFT) {
1079                         xlog_warn("XFS: Log sector size too small "
1080                                 "(0x%x < 0x%x)", log2_size, BBSHIFT);
1081                         goto out_free_log;
1082                 }
1083
1084                 log2_size -= BBSHIFT;
1085                 if (log2_size > mp->m_sectbb_log) {
1086                         xlog_warn("XFS: Log sector size too large "
1087                                 "(0x%x > 0x%x)", log2_size, mp->m_sectbb_log);
1088                         goto out_free_log;
1089                 }
1090
1091                 /* for larger sector sizes, must have v2 or external log */
1092                 if (log2_size && log->l_logBBstart > 0 &&
1093                             !xfs_sb_version_haslogv2(&mp->m_sb)) {
1094
1095                         xlog_warn("XFS: log sector size (0x%x) invalid "
1096                                   "for configuration.", log2_size);
1097                         goto out_free_log;
1098                 }
1099         }
1100         log->l_sectBBsize = 1 << log2_size;
1101
1102         xlog_get_iclog_buffer_size(mp, log);
1103
1104         error = ENOMEM;
1105         bp = xfs_buf_get_empty(log->l_iclog_size, mp->m_logdev_targp);
1106         if (!bp)
1107                 goto out_free_log;
1108         XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1109         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
1110         ASSERT(XFS_BUF_ISBUSY(bp));
1111         ASSERT(XFS_BUF_VALUSEMA(bp) <= 0);
1112         log->l_xbuf = bp;
1113
1114         spin_lock_init(&log->l_icloglock);
1115         spin_lock_init(&log->l_grant_lock);
1116         sv_init(&log->l_flush_wait, 0, "flush_wait");
1117
1118         /* log record size must be multiple of BBSIZE; see xlog_rec_header_t */
1119         ASSERT((XFS_BUF_SIZE(bp) & BBMASK) == 0);
1120
1121         iclogp = &log->l_iclog;
1122         /*
1123          * The amount of memory to allocate for the iclog structure is
1124          * rather funky due to the way the structure is defined.  It is
1125          * done this way so that we can use different sizes for machines
1126          * with different amounts of memory.  See the definition of
1127          * xlog_in_core_t in xfs_log_priv.h for details.
1128          */
1129         iclogsize = log->l_iclog_size;
1130         ASSERT(log->l_iclog_size >= 4096);
1131         for (i=0; i < log->l_iclog_bufs; i++) {
1132                 *iclogp = kmem_zalloc(sizeof(xlog_in_core_t), KM_MAYFAIL);
1133                 if (!*iclogp)
1134                         goto out_free_iclog;
1135
1136                 iclog = *iclogp;
1137                 iclog->ic_prev = prev_iclog;
1138                 prev_iclog = iclog;
1139
1140                 bp = xfs_buf_get_noaddr(log->l_iclog_size, mp->m_logdev_targp);
1141                 if (!bp)
1142                         goto out_free_iclog;
1143                 if (!XFS_BUF_CPSEMA(bp))
1144                         ASSERT(0);
1145                 XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1146                 XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
1147                 iclog->ic_bp = bp;
1148                 iclog->ic_data = bp->b_addr;
1149 #ifdef DEBUG
1150                 log->l_iclog_bak[i] = (xfs_caddr_t)&(iclog->ic_header);
1151 #endif
1152                 head = &iclog->ic_header;
1153                 memset(head, 0, sizeof(xlog_rec_header_t));
1154                 head->h_magicno = cpu_to_be32(XLOG_HEADER_MAGIC_NUM);
1155                 head->h_version = cpu_to_be32(
1156                         xfs_sb_version_haslogv2(&log->l_mp->m_sb) ? 2 : 1);
1157                 head->h_size = cpu_to_be32(log->l_iclog_size);
1158                 /* new fields */
1159                 head->h_fmt = cpu_to_be32(XLOG_FMT);
1160                 memcpy(&head->h_fs_uuid, &mp->m_sb.sb_uuid, sizeof(uuid_t));
1161
1162                 iclog->ic_size = XFS_BUF_SIZE(bp) - log->l_iclog_hsize;
1163                 iclog->ic_state = XLOG_STATE_ACTIVE;
1164                 iclog->ic_log = log;
1165                 atomic_set(&iclog->ic_refcnt, 0);
1166                 spin_lock_init(&iclog->ic_callback_lock);
1167                 iclog->ic_callback_tail = &(iclog->ic_callback);
1168                 iclog->ic_datap = (char *)iclog->ic_data + log->l_iclog_hsize;
1169
1170                 ASSERT(XFS_BUF_ISBUSY(iclog->ic_bp));
1171                 ASSERT(XFS_BUF_VALUSEMA(iclog->ic_bp) <= 0);
1172                 sv_init(&iclog->ic_force_wait, SV_DEFAULT, "iclog-force");
1173                 sv_init(&iclog->ic_write_wait, SV_DEFAULT, "iclog-write");
1174
1175                 iclogp = &iclog->ic_next;
1176         }
1177         *iclogp = log->l_iclog;                 /* complete ring */
1178         log->l_iclog->ic_prev = prev_iclog;     /* re-write 1st prev ptr */
1179
1180         error = xlog_cil_init(log);
1181         if (error)
1182                 goto out_free_iclog;
1183         return log;
1184
1185 out_free_iclog:
1186         for (iclog = log->l_iclog; iclog; iclog = prev_iclog) {
1187                 prev_iclog = iclog->ic_next;
1188                 if (iclog->ic_bp) {
1189                         sv_destroy(&iclog->ic_force_wait);
1190                         sv_destroy(&iclog->ic_write_wait);
1191                         xfs_buf_free(iclog->ic_bp);
1192                 }
1193                 kmem_free(iclog);
1194         }
1195         spinlock_destroy(&log->l_icloglock);
1196         spinlock_destroy(&log->l_grant_lock);
1197         xfs_buf_free(log->l_xbuf);
1198 out_free_log:
1199         kmem_free(log);
1200 out:
1201         return ERR_PTR(-error);
1202 }       /* xlog_alloc_log */
1203
1204
1205 /*
1206  * Write out the commit record of a transaction associated with the given
1207  * ticket.  Return the lsn of the commit record.
1208  */
1209 STATIC int
1210 xlog_commit_record(
1211         struct log              *log,
1212         struct xlog_ticket      *ticket,
1213         struct xlog_in_core     **iclog,
1214         xfs_lsn_t               *commitlsnp)
1215 {
1216         struct xfs_mount *mp = log->l_mp;
1217         int     error;
1218         struct xfs_log_iovec reg = {
1219                 .i_addr = NULL,
1220                 .i_len = 0,
1221                 .i_type = XLOG_REG_TYPE_COMMIT,
1222         };
1223         struct xfs_log_vec vec = {
1224                 .lv_niovecs = 1,
1225                 .lv_iovecp = &reg,
1226         };
1227
1228         ASSERT_ALWAYS(iclog);
1229         error = xlog_write(log, &vec, ticket, commitlsnp, iclog,
1230                                         XLOG_COMMIT_TRANS);
1231         if (error)
1232                 xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR);
1233         return error;
1234 }
1235
1236 /*
1237  * Push on the buffer cache code if we ever use more than 75% of the on-disk
1238  * log space.  This code pushes on the lsn which would supposedly free up
1239  * the 25% which we want to leave free.  We may need to adopt a policy which
1240  * pushes on an lsn which is further along in the log once we reach the high
1241  * water mark.  In this manner, we would be creating a low water mark.
1242  */
1243 STATIC void
1244 xlog_grant_push_ail(xfs_mount_t *mp,
1245                     int         need_bytes)
1246 {
1247     xlog_t      *log = mp->m_log;       /* pointer to the log */
1248     xfs_lsn_t   tail_lsn;               /* lsn of the log tail */
1249     xfs_lsn_t   threshold_lsn = 0;      /* lsn we'd like to be at */
1250     int         free_blocks;            /* free blocks left to write to */
1251     int         free_bytes;             /* free bytes left to write to */
1252     int         threshold_block;        /* block in lsn we'd like to be at */
1253     int         threshold_cycle;        /* lsn cycle we'd like to be at */
1254     int         free_threshold;
1255
1256     ASSERT(BTOBB(need_bytes) < log->l_logBBsize);
1257
1258     spin_lock(&log->l_grant_lock);
1259     free_bytes = xlog_space_left(log,
1260                                  log->l_grant_reserve_cycle,
1261                                  log->l_grant_reserve_bytes);
1262     tail_lsn = log->l_tail_lsn;
1263     free_blocks = BTOBBT(free_bytes);
1264
1265     /*
1266      * Set the threshold for the minimum number of free blocks in the
1267      * log to the maximum of what the caller needs, one quarter of the
1268      * log, and 256 blocks.
1269      */
1270     free_threshold = BTOBB(need_bytes);
1271     free_threshold = MAX(free_threshold, (log->l_logBBsize >> 2));
1272     free_threshold = MAX(free_threshold, 256);
1273     if (free_blocks < free_threshold) {
1274         threshold_block = BLOCK_LSN(tail_lsn) + free_threshold;
1275         threshold_cycle = CYCLE_LSN(tail_lsn);
1276         if (threshold_block >= log->l_logBBsize) {
1277             threshold_block -= log->l_logBBsize;
1278             threshold_cycle += 1;
1279         }
1280         threshold_lsn = xlog_assign_lsn(threshold_cycle, threshold_block);
1281
1282         /* Don't pass in an lsn greater than the lsn of the last
1283          * log record known to be on disk.
1284          */
1285         if (XFS_LSN_CMP(threshold_lsn, log->l_last_sync_lsn) > 0)
1286             threshold_lsn = log->l_last_sync_lsn;
1287     }
1288     spin_unlock(&log->l_grant_lock);
1289
1290     /*
1291      * Get the transaction layer to kick the dirty buffers out to
1292      * disk asynchronously. No point in trying to do this if
1293      * the filesystem is shutting down.
1294      */
1295     if (threshold_lsn &&
1296         !XLOG_FORCED_SHUTDOWN(log))
1297             xfs_trans_ail_push(log->l_ailp, threshold_lsn);
1298 }       /* xlog_grant_push_ail */
1299
1300 /*
1301  * The bdstrat callback function for log bufs. This gives us a central
1302  * place to trap bufs in case we get hit by a log I/O error and need to
1303  * shutdown. Actually, in practice, even when we didn't get a log error,
1304  * we transition the iclogs to IOERROR state *after* flushing all existing
1305  * iclogs to disk. This is because we don't want anymore new transactions to be
1306  * started or completed afterwards.
1307  */
1308 STATIC int
1309 xlog_bdstrat(
1310         struct xfs_buf          *bp)
1311 {
1312         struct xlog_in_core     *iclog;
1313
1314         iclog = XFS_BUF_FSPRIVATE(bp, xlog_in_core_t *);
1315         if (iclog->ic_state & XLOG_STATE_IOERROR) {
1316                 XFS_BUF_ERROR(bp, EIO);
1317                 XFS_BUF_STALE(bp);
1318                 xfs_biodone(bp);
1319                 /*
1320                  * It would seem logical to return EIO here, but we rely on
1321                  * the log state machine to propagate I/O errors instead of
1322                  * doing it here.
1323                  */
1324                 return 0;
1325         }
1326
1327         bp->b_flags |= _XBF_RUN_QUEUES;
1328         xfs_buf_iorequest(bp);
1329         return 0;
1330 }
1331
1332 /*
1333  * Flush out the in-core log (iclog) to the on-disk log in an asynchronous 
1334  * fashion.  Previously, we should have moved the current iclog
1335  * ptr in the log to point to the next available iclog.  This allows further
1336  * write to continue while this code syncs out an iclog ready to go.
1337  * Before an in-core log can be written out, the data section must be scanned
1338  * to save away the 1st word of each BBSIZE block into the header.  We replace
1339  * it with the current cycle count.  Each BBSIZE block is tagged with the
1340  * cycle count because there in an implicit assumption that drives will
1341  * guarantee that entire 512 byte blocks get written at once.  In other words,
1342  * we can't have part of a 512 byte block written and part not written.  By
1343  * tagging each block, we will know which blocks are valid when recovering
1344  * after an unclean shutdown.
1345  *
1346  * This routine is single threaded on the iclog.  No other thread can be in
1347  * this routine with the same iclog.  Changing contents of iclog can there-
1348  * fore be done without grabbing the state machine lock.  Updating the global
1349  * log will require grabbing the lock though.
1350  *
1351  * The entire log manager uses a logical block numbering scheme.  Only
1352  * log_sync (and then only bwrite()) know about the fact that the log may
1353  * not start with block zero on a given device.  The log block start offset
1354  * is added immediately before calling bwrite().
1355  */
1356
1357 STATIC int
1358 xlog_sync(xlog_t                *log,
1359           xlog_in_core_t        *iclog)
1360 {
1361         xfs_caddr_t     dptr;           /* pointer to byte sized element */
1362         xfs_buf_t       *bp;
1363         int             i;
1364         uint            count;          /* byte count of bwrite */
1365         uint            count_init;     /* initial count before roundup */
1366         int             roundoff;       /* roundoff to BB or stripe */
1367         int             split = 0;      /* split write into two regions */
1368         int             error;
1369         int             v2 = xfs_sb_version_haslogv2(&log->l_mp->m_sb);
1370
1371         XFS_STATS_INC(xs_log_writes);
1372         ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
1373
1374         /* Add for LR header */
1375         count_init = log->l_iclog_hsize + iclog->ic_offset;
1376
1377         /* Round out the log write size */
1378         if (v2 && log->l_mp->m_sb.sb_logsunit > 1) {
1379                 /* we have a v2 stripe unit to use */
1380                 count = XLOG_LSUNITTOB(log, XLOG_BTOLSUNIT(log, count_init));
1381         } else {
1382                 count = BBTOB(BTOBB(count_init));
1383         }
1384         roundoff = count - count_init;
1385         ASSERT(roundoff >= 0);
1386         ASSERT((v2 && log->l_mp->m_sb.sb_logsunit > 1 && 
1387                 roundoff < log->l_mp->m_sb.sb_logsunit)
1388                 || 
1389                 (log->l_mp->m_sb.sb_logsunit <= 1 && 
1390                  roundoff < BBTOB(1)));
1391
1392         /* move grant heads by roundoff in sync */
1393         spin_lock(&log->l_grant_lock);
1394         xlog_grant_add_space(log, roundoff);
1395         spin_unlock(&log->l_grant_lock);
1396
1397         /* put cycle number in every block */
1398         xlog_pack_data(log, iclog, roundoff); 
1399
1400         /* real byte length */
1401         if (v2) {
1402                 iclog->ic_header.h_len =
1403                         cpu_to_be32(iclog->ic_offset + roundoff);
1404         } else {
1405                 iclog->ic_header.h_len =
1406                         cpu_to_be32(iclog->ic_offset);
1407         }
1408
1409         bp = iclog->ic_bp;
1410         ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) == (unsigned long)1);
1411         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1412         XFS_BUF_SET_ADDR(bp, BLOCK_LSN(be64_to_cpu(iclog->ic_header.h_lsn)));
1413
1414         XFS_STATS_ADD(xs_log_blocks, BTOBB(count));
1415
1416         /* Do we need to split this write into 2 parts? */
1417         if (XFS_BUF_ADDR(bp) + BTOBB(count) > log->l_logBBsize) {
1418                 split = count - (BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp)));
1419                 count = BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp));
1420                 iclog->ic_bwritecnt = 2;        /* split into 2 writes */
1421         } else {
1422                 iclog->ic_bwritecnt = 1;
1423         }
1424         XFS_BUF_SET_COUNT(bp, count);
1425         XFS_BUF_SET_FSPRIVATE(bp, iclog);       /* save for later */
1426         XFS_BUF_ZEROFLAGS(bp);
1427         XFS_BUF_BUSY(bp);
1428         XFS_BUF_ASYNC(bp);
1429         bp->b_flags |= XBF_LOG_BUFFER;
1430         /*
1431          * Do an ordered write for the log block.
1432          * Its unnecessary to flush the first split block in the log wrap case.
1433          */
1434         if (!split && (log->l_mp->m_flags & XFS_MOUNT_BARRIER))
1435                 XFS_BUF_ORDERED(bp);
1436
1437         ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1438         ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1439
1440         xlog_verify_iclog(log, iclog, count, B_TRUE);
1441
1442         /* account for log which doesn't start at block #0 */
1443         XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1444         /*
1445          * Don't call xfs_bwrite here. We do log-syncs even when the filesystem
1446          * is shutting down.
1447          */
1448         XFS_BUF_WRITE(bp);
1449
1450         if ((error = xlog_bdstrat(bp))) {
1451                 xfs_ioerror_alert("xlog_sync", log->l_mp, bp,
1452                                   XFS_BUF_ADDR(bp));
1453                 return error;
1454         }
1455         if (split) {
1456                 bp = iclog->ic_log->l_xbuf;
1457                 ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) ==
1458                                                         (unsigned long)1);
1459                 XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1460                 XFS_BUF_SET_ADDR(bp, 0);             /* logical 0 */
1461                 XFS_BUF_SET_PTR(bp, (xfs_caddr_t)((__psint_t)&(iclog->ic_header)+
1462                                             (__psint_t)count), split);
1463                 XFS_BUF_SET_FSPRIVATE(bp, iclog);
1464                 XFS_BUF_ZEROFLAGS(bp);
1465                 XFS_BUF_BUSY(bp);
1466                 XFS_BUF_ASYNC(bp);
1467                 bp->b_flags |= XBF_LOG_BUFFER;
1468                 if (log->l_mp->m_flags & XFS_MOUNT_BARRIER)
1469                         XFS_BUF_ORDERED(bp);
1470                 dptr = XFS_BUF_PTR(bp);
1471                 /*
1472                  * Bump the cycle numbers at the start of each block
1473                  * since this part of the buffer is at the start of
1474                  * a new cycle.  Watch out for the header magic number
1475                  * case, though.
1476                  */
1477                 for (i = 0; i < split; i += BBSIZE) {
1478                         be32_add_cpu((__be32 *)dptr, 1);
1479                         if (be32_to_cpu(*(__be32 *)dptr) == XLOG_HEADER_MAGIC_NUM)
1480                                 be32_add_cpu((__be32 *)dptr, 1);
1481                         dptr += BBSIZE;
1482                 }
1483
1484                 ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1485                 ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1486
1487                 /* account for internal log which doesn't start at block #0 */
1488                 XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1489                 XFS_BUF_WRITE(bp);
1490                 if ((error = xlog_bdstrat(bp))) {
1491                         xfs_ioerror_alert("xlog_sync (split)", log->l_mp,
1492                                           bp, XFS_BUF_ADDR(bp));
1493                         return error;
1494                 }
1495         }
1496         return 0;
1497 }       /* xlog_sync */
1498
1499
1500 /*
1501  * Deallocate a log structure
1502  */
1503 STATIC void
1504 xlog_dealloc_log(xlog_t *log)
1505 {
1506         xlog_in_core_t  *iclog, *next_iclog;
1507         int             i;
1508
1509         xlog_cil_destroy(log);
1510
1511         iclog = log->l_iclog;
1512         for (i=0; i<log->l_iclog_bufs; i++) {
1513                 sv_destroy(&iclog->ic_force_wait);
1514                 sv_destroy(&iclog->ic_write_wait);
1515                 xfs_buf_free(iclog->ic_bp);
1516                 next_iclog = iclog->ic_next;
1517                 kmem_free(iclog);
1518                 iclog = next_iclog;
1519         }
1520         spinlock_destroy(&log->l_icloglock);
1521         spinlock_destroy(&log->l_grant_lock);
1522
1523         xfs_buf_free(log->l_xbuf);
1524         log->l_mp->m_log = NULL;
1525         kmem_free(log);
1526 }       /* xlog_dealloc_log */
1527
1528 /*
1529  * Update counters atomically now that memcpy is done.
1530  */
1531 /* ARGSUSED */
1532 static inline void
1533 xlog_state_finish_copy(xlog_t           *log,
1534                        xlog_in_core_t   *iclog,
1535                        int              record_cnt,
1536                        int              copy_bytes)
1537 {
1538         spin_lock(&log->l_icloglock);
1539
1540         be32_add_cpu(&iclog->ic_header.h_num_logops, record_cnt);
1541         iclog->ic_offset += copy_bytes;
1542
1543         spin_unlock(&log->l_icloglock);
1544 }       /* xlog_state_finish_copy */
1545
1546
1547
1548
1549 /*
1550  * print out info relating to regions written which consume
1551  * the reservation
1552  */
1553 void
1554 xlog_print_tic_res(
1555         struct xfs_mount        *mp,
1556         struct xlog_ticket      *ticket)
1557 {
1558         uint i;
1559         uint ophdr_spc = ticket->t_res_num_ophdrs * (uint)sizeof(xlog_op_header_t);
1560
1561         /* match with XLOG_REG_TYPE_* in xfs_log.h */
1562         static char *res_type_str[XLOG_REG_TYPE_MAX] = {
1563             "bformat",
1564             "bchunk",
1565             "efi_format",
1566             "efd_format",
1567             "iformat",
1568             "icore",
1569             "iext",
1570             "ibroot",
1571             "ilocal",
1572             "iattr_ext",
1573             "iattr_broot",
1574             "iattr_local",
1575             "qformat",
1576             "dquot",
1577             "quotaoff",
1578             "LR header",
1579             "unmount",
1580             "commit",
1581             "trans header"
1582         };
1583         static char *trans_type_str[XFS_TRANS_TYPE_MAX] = {
1584             "SETATTR_NOT_SIZE",
1585             "SETATTR_SIZE",
1586             "INACTIVE",
1587             "CREATE",
1588             "CREATE_TRUNC",
1589             "TRUNCATE_FILE",
1590             "REMOVE",
1591             "LINK",
1592             "RENAME",
1593             "MKDIR",
1594             "RMDIR",
1595             "SYMLINK",
1596             "SET_DMATTRS",
1597             "GROWFS",
1598             "STRAT_WRITE",
1599             "DIOSTRAT",
1600             "WRITE_SYNC",
1601             "WRITEID",
1602             "ADDAFORK",
1603             "ATTRINVAL",
1604             "ATRUNCATE",
1605             "ATTR_SET",
1606             "ATTR_RM",
1607             "ATTR_FLAG",
1608             "CLEAR_AGI_BUCKET",
1609             "QM_SBCHANGE",
1610             "DUMMY1",
1611             "DUMMY2",
1612             "QM_QUOTAOFF",
1613             "QM_DQALLOC",
1614             "QM_SETQLIM",
1615             "QM_DQCLUSTER",
1616             "QM_QINOCREATE",
1617             "QM_QUOTAOFF_END",
1618             "SB_UNIT",
1619             "FSYNC_TS",
1620             "GROWFSRT_ALLOC",
1621             "GROWFSRT_ZERO",
1622             "GROWFSRT_FREE",
1623             "SWAPEXT"
1624         };
1625
1626         xfs_fs_cmn_err(CE_WARN, mp,
1627                         "xfs_log_write: reservation summary:\n"
1628                         "  trans type  = %s (%u)\n"
1629                         "  unit res    = %d bytes\n"
1630                         "  current res = %d bytes\n"
1631                         "  total reg   = %u bytes (o/flow = %u bytes)\n"
1632                         "  ophdrs      = %u (ophdr space = %u bytes)\n"
1633                         "  ophdr + reg = %u bytes\n"
1634                         "  num regions = %u\n",
1635                         ((ticket->t_trans_type <= 0 ||
1636                           ticket->t_trans_type > XFS_TRANS_TYPE_MAX) ?
1637                           "bad-trans-type" : trans_type_str[ticket->t_trans_type-1]),
1638                         ticket->t_trans_type,
1639                         ticket->t_unit_res,
1640                         ticket->t_curr_res,
1641                         ticket->t_res_arr_sum, ticket->t_res_o_flow,
1642                         ticket->t_res_num_ophdrs, ophdr_spc,
1643                         ticket->t_res_arr_sum + 
1644                         ticket->t_res_o_flow + ophdr_spc,
1645                         ticket->t_res_num);
1646
1647         for (i = 0; i < ticket->t_res_num; i++) {
1648                 uint r_type = ticket->t_res_arr[i].r_type; 
1649                 cmn_err(CE_WARN,
1650                             "region[%u]: %s - %u bytes\n",
1651                             i, 
1652                             ((r_type <= 0 || r_type > XLOG_REG_TYPE_MAX) ?
1653                             "bad-rtype" : res_type_str[r_type-1]),
1654                             ticket->t_res_arr[i].r_len);
1655         }
1656
1657         xfs_cmn_err(XFS_PTAG_LOGRES, CE_ALERT, mp,
1658                 "xfs_log_write: reservation ran out. Need to up reservation");
1659         xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
1660 }
1661
1662 /*
1663  * Calculate the potential space needed by the log vector.  Each region gets
1664  * its own xlog_op_header_t and may need to be double word aligned.
1665  */
1666 static int
1667 xlog_write_calc_vec_length(
1668         struct xlog_ticket      *ticket,
1669         struct xfs_log_vec      *log_vector)
1670 {
1671         struct xfs_log_vec      *lv;
1672         int                     headers = 0;
1673         int                     len = 0;
1674         int                     i;
1675
1676         /* acct for start rec of xact */
1677         if (ticket->t_flags & XLOG_TIC_INITED)
1678                 headers++;
1679
1680         for (lv = log_vector; lv; lv = lv->lv_next) {
1681                 headers += lv->lv_niovecs;
1682
1683                 for (i = 0; i < lv->lv_niovecs; i++) {
1684                         struct xfs_log_iovec    *vecp = &lv->lv_iovecp[i];
1685
1686                         len += vecp->i_len;
1687                         xlog_tic_add_region(ticket, vecp->i_len, vecp->i_type);
1688                 }
1689         }
1690
1691         ticket->t_res_num_ophdrs += headers;
1692         len += headers * sizeof(struct xlog_op_header);
1693
1694         return len;
1695 }
1696
1697 /*
1698  * If first write for transaction, insert start record  We can't be trying to
1699  * commit if we are inited.  We can't have any "partial_copy" if we are inited.
1700  */
1701 static int
1702 xlog_write_start_rec(
1703         struct xlog_op_header   *ophdr,
1704         struct xlog_ticket      *ticket)
1705 {
1706         if (!(ticket->t_flags & XLOG_TIC_INITED))
1707                 return 0;
1708
1709         ophdr->oh_tid   = cpu_to_be32(ticket->t_tid);
1710         ophdr->oh_clientid = ticket->t_clientid;
1711         ophdr->oh_len = 0;
1712         ophdr->oh_flags = XLOG_START_TRANS;
1713         ophdr->oh_res2 = 0;
1714
1715         ticket->t_flags &= ~XLOG_TIC_INITED;
1716
1717         return sizeof(struct xlog_op_header);
1718 }
1719
1720 static xlog_op_header_t *
1721 xlog_write_setup_ophdr(
1722         struct log              *log,
1723         struct xlog_op_header   *ophdr,
1724         struct xlog_ticket      *ticket,
1725         uint                    flags)
1726 {
1727         ophdr->oh_tid = cpu_to_be32(ticket->t_tid);
1728         ophdr->oh_clientid = ticket->t_clientid;
1729         ophdr->oh_res2 = 0;
1730
1731         /* are we copying a commit or unmount record? */
1732         ophdr->oh_flags = flags;
1733
1734         /*
1735          * We've seen logs corrupted with bad transaction client ids.  This
1736          * makes sure that XFS doesn't generate them on.  Turn this into an EIO
1737          * and shut down the filesystem.
1738          */
1739         switch (ophdr->oh_clientid)  {
1740         case XFS_TRANSACTION:
1741         case XFS_VOLUME:
1742         case XFS_LOG:
1743                 break;
1744         default:
1745                 xfs_fs_cmn_err(CE_WARN, log->l_mp,
1746                         "Bad XFS transaction clientid 0x%x in ticket 0x%p",
1747                         ophdr->oh_clientid, ticket);
1748                 return NULL;
1749         }
1750
1751         return ophdr;
1752 }
1753
1754 /*
1755  * Set up the parameters of the region copy into the log. This has
1756  * to handle region write split across multiple log buffers - this
1757  * state is kept external to this function so that this code can
1758  * can be written in an obvious, self documenting manner.
1759  */
1760 static int
1761 xlog_write_setup_copy(
1762         struct xlog_ticket      *ticket,
1763         struct xlog_op_header   *ophdr,
1764         int                     space_available,
1765         int                     space_required,
1766         int                     *copy_off,
1767         int                     *copy_len,
1768         int                     *last_was_partial_copy,
1769         int                     *bytes_consumed)
1770 {
1771         int                     still_to_copy;
1772
1773         still_to_copy = space_required - *bytes_consumed;
1774         *copy_off = *bytes_consumed;
1775
1776         if (still_to_copy <= space_available) {
1777                 /* write of region completes here */
1778                 *copy_len = still_to_copy;
1779                 ophdr->oh_len = cpu_to_be32(*copy_len);
1780                 if (*last_was_partial_copy)
1781                         ophdr->oh_flags |= (XLOG_END_TRANS|XLOG_WAS_CONT_TRANS);
1782                 *last_was_partial_copy = 0;
1783                 *bytes_consumed = 0;
1784                 return 0;
1785         }
1786
1787         /* partial write of region, needs extra log op header reservation */
1788         *copy_len = space_available;
1789         ophdr->oh_len = cpu_to_be32(*copy_len);
1790         ophdr->oh_flags |= XLOG_CONTINUE_TRANS;
1791         if (*last_was_partial_copy)
1792                 ophdr->oh_flags |= XLOG_WAS_CONT_TRANS;
1793         *bytes_consumed += *copy_len;
1794         (*last_was_partial_copy)++;
1795
1796         /* account for new log op header */
1797         ticket->t_curr_res -= sizeof(struct xlog_op_header);
1798         ticket->t_res_num_ophdrs++;
1799
1800         return sizeof(struct xlog_op_header);
1801 }
1802
1803 static int
1804 xlog_write_copy_finish(
1805         struct log              *log,
1806         struct xlog_in_core     *iclog,
1807         uint                    flags,
1808         int                     *record_cnt,
1809         int                     *data_cnt,
1810         int                     *partial_copy,
1811         int                     *partial_copy_len,
1812         int                     log_offset,
1813         struct xlog_in_core     **commit_iclog)
1814 {
1815         if (*partial_copy) {
1816                 /*
1817                  * This iclog has already been marked WANT_SYNC by
1818                  * xlog_state_get_iclog_space.
1819                  */
1820                 xlog_state_finish_copy(log, iclog, *record_cnt, *data_cnt);
1821                 *record_cnt = 0;
1822                 *data_cnt = 0;
1823                 return xlog_state_release_iclog(log, iclog);
1824         }
1825
1826         *partial_copy = 0;
1827         *partial_copy_len = 0;
1828
1829         if (iclog->ic_size - log_offset <= sizeof(xlog_op_header_t)) {
1830                 /* no more space in this iclog - push it. */
1831                 xlog_state_finish_copy(log, iclog, *record_cnt, *data_cnt);
1832                 *record_cnt = 0;
1833                 *data_cnt = 0;
1834
1835                 spin_lock(&log->l_icloglock);
1836                 xlog_state_want_sync(log, iclog);
1837                 spin_unlock(&log->l_icloglock);
1838
1839                 if (!commit_iclog)
1840                         return xlog_state_release_iclog(log, iclog);
1841                 ASSERT(flags & XLOG_COMMIT_TRANS);
1842                 *commit_iclog = iclog;
1843         }
1844
1845         return 0;
1846 }
1847
1848 /*
1849  * Write some region out to in-core log
1850  *
1851  * This will be called when writing externally provided regions or when
1852  * writing out a commit record for a given transaction.
1853  *
1854  * General algorithm:
1855  *      1. Find total length of this write.  This may include adding to the
1856  *              lengths passed in.
1857  *      2. Check whether we violate the tickets reservation.
1858  *      3. While writing to this iclog
1859  *          A. Reserve as much space in this iclog as can get
1860  *          B. If this is first write, save away start lsn
1861  *          C. While writing this region:
1862  *              1. If first write of transaction, write start record
1863  *              2. Write log operation header (header per region)
1864  *              3. Find out if we can fit entire region into this iclog
1865  *              4. Potentially, verify destination memcpy ptr
1866  *              5. Memcpy (partial) region
1867  *              6. If partial copy, release iclog; otherwise, continue
1868  *                      copying more regions into current iclog
1869  *      4. Mark want sync bit (in simulation mode)
1870  *      5. Release iclog for potential flush to on-disk log.
1871  *
1872  * ERRORS:
1873  * 1.   Panic if reservation is overrun.  This should never happen since
1874  *      reservation amounts are generated internal to the filesystem.
1875  * NOTES:
1876  * 1. Tickets are single threaded data structures.
1877  * 2. The XLOG_END_TRANS & XLOG_CONTINUE_TRANS flags are passed down to the
1878  *      syncing routine.  When a single log_write region needs to span
1879  *      multiple in-core logs, the XLOG_CONTINUE_TRANS bit should be set
1880  *      on all log operation writes which don't contain the end of the
1881  *      region.  The XLOG_END_TRANS bit is used for the in-core log
1882  *      operation which contains the end of the continued log_write region.
1883  * 3. When xlog_state_get_iclog_space() grabs the rest of the current iclog,
1884  *      we don't really know exactly how much space will be used.  As a result,
1885  *      we don't update ic_offset until the end when we know exactly how many
1886  *      bytes have been written out.
1887  */
1888 int
1889 xlog_write(
1890         struct log              *log,
1891         struct xfs_log_vec      *log_vector,
1892         struct xlog_ticket      *ticket,
1893         xfs_lsn_t               *start_lsn,
1894         struct xlog_in_core     **commit_iclog,
1895         uint                    flags)
1896 {
1897         struct xlog_in_core     *iclog = NULL;
1898         struct xfs_log_iovec    *vecp;
1899         struct xfs_log_vec      *lv;
1900         int                     len;
1901         int                     index;
1902         int                     partial_copy = 0;
1903         int                     partial_copy_len = 0;
1904         int                     contwr = 0;
1905         int                     record_cnt = 0;
1906         int                     data_cnt = 0;
1907         int                     error;
1908
1909         *start_lsn = 0;
1910
1911         len = xlog_write_calc_vec_length(ticket, log_vector);
1912         if (log->l_cilp) {
1913                 /*
1914                  * Region headers and bytes are already accounted for.
1915                  * We only need to take into account start records and
1916                  * split regions in this function.
1917                  */
1918                 if (ticket->t_flags & XLOG_TIC_INITED)
1919                         ticket->t_curr_res -= sizeof(xlog_op_header_t);
1920
1921                 /*
1922                  * Commit record headers need to be accounted for. These
1923                  * come in as separate writes so are easy to detect.
1924                  */
1925                 if (flags & (XLOG_COMMIT_TRANS | XLOG_UNMOUNT_TRANS))
1926                         ticket->t_curr_res -= sizeof(xlog_op_header_t);
1927         } else
1928                 ticket->t_curr_res -= len;
1929
1930         if (ticket->t_curr_res < 0)
1931                 xlog_print_tic_res(log->l_mp, ticket);
1932
1933         index = 0;
1934         lv = log_vector;
1935         vecp = lv->lv_iovecp;
1936         while (lv && index < lv->lv_niovecs) {
1937                 void            *ptr;
1938                 int             log_offset;
1939
1940                 error = xlog_state_get_iclog_space(log, len, &iclog, ticket,
1941                                                    &contwr, &log_offset);
1942                 if (error)
1943                         return error;
1944
1945                 ASSERT(log_offset <= iclog->ic_size - 1);
1946                 ptr = iclog->ic_datap + log_offset;
1947
1948                 /* start_lsn is the first lsn written to. That's all we need. */
1949                 if (!*start_lsn)
1950                         *start_lsn = be64_to_cpu(iclog->ic_header.h_lsn);
1951
1952                 /*
1953                  * This loop writes out as many regions as can fit in the amount
1954                  * of space which was allocated by xlog_state_get_iclog_space().
1955                  */
1956                 while (lv && index < lv->lv_niovecs) {
1957                         struct xfs_log_iovec    *reg = &vecp[index];
1958                         struct xlog_op_header   *ophdr;
1959                         int                     start_rec_copy;
1960                         int                     copy_len;
1961                         int                     copy_off;
1962
1963                         ASSERT(reg->i_len % sizeof(__int32_t) == 0);
1964                         ASSERT((unsigned long)ptr % sizeof(__int32_t) == 0);
1965
1966                         start_rec_copy = xlog_write_start_rec(ptr, ticket);
1967                         if (start_rec_copy) {
1968                                 record_cnt++;
1969                                 xlog_write_adv_cnt(&ptr, &len, &log_offset,
1970                                                    start_rec_copy);
1971                         }
1972
1973                         ophdr = xlog_write_setup_ophdr(log, ptr, ticket, flags);
1974                         if (!ophdr)
1975                                 return XFS_ERROR(EIO);
1976
1977                         xlog_write_adv_cnt(&ptr, &len, &log_offset,
1978                                            sizeof(struct xlog_op_header));
1979
1980                         len += xlog_write_setup_copy(ticket, ophdr,
1981                                                      iclog->ic_size-log_offset,
1982                                                      reg->i_len,
1983                                                      &copy_off, &copy_len,
1984                                                      &partial_copy,
1985                                                      &partial_copy_len);
1986                         xlog_verify_dest_ptr(log, ptr);
1987
1988                         /* copy region */
1989                         ASSERT(copy_len >= 0);
1990                         memcpy(ptr, reg->i_addr + copy_off, copy_len);
1991                         xlog_write_adv_cnt(&ptr, &len, &log_offset, copy_len);
1992
1993                         copy_len += start_rec_copy + sizeof(xlog_op_header_t);
1994                         record_cnt++;
1995                         data_cnt += contwr ? copy_len : 0;
1996
1997                         error = xlog_write_copy_finish(log, iclog, flags,
1998                                                        &record_cnt, &data_cnt,
1999                                                        &partial_copy,
2000                                                        &partial_copy_len,
2001                                                        log_offset,
2002                                                        commit_iclog);
2003                         if (error)
2004                                 return error;
2005
2006                         /*
2007                          * if we had a partial copy, we need to get more iclog
2008                          * space but we don't want to increment the region
2009                          * index because there is still more is this region to
2010                          * write.
2011                          *
2012                          * If we completed writing this region, and we flushed
2013                          * the iclog (indicated by resetting of the record
2014                          * count), then we also need to get more log space. If
2015                          * this was the last record, though, we are done and
2016                          * can just return.
2017                          */
2018                         if (partial_copy)
2019                                 break;
2020
2021                         if (++index == lv->lv_niovecs) {
2022                                 lv = lv->lv_next;
2023                                 index = 0;
2024                                 if (lv)
2025                                         vecp = lv->lv_iovecp;
2026                         }
2027                         if (record_cnt == 0) {
2028                                 if (!lv)
2029                                         return 0;
2030                                 break;
2031                         }
2032                 }
2033         }
2034
2035         ASSERT(len == 0);
2036
2037         xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
2038         if (!commit_iclog)
2039                 return xlog_state_release_iclog(log, iclog);
2040
2041         ASSERT(flags & XLOG_COMMIT_TRANS);
2042         *commit_iclog = iclog;
2043         return 0;
2044 }
2045
2046
2047 /*****************************************************************************
2048  *
2049  *              State Machine functions
2050  *
2051  *****************************************************************************
2052  */
2053
2054 /* Clean iclogs starting from the head.  This ordering must be
2055  * maintained, so an iclog doesn't become ACTIVE beyond one that
2056  * is SYNCING.  This is also required to maintain the notion that we use
2057  * a ordered wait queue to hold off would be writers to the log when every
2058  * iclog is trying to sync to disk.
2059  *
2060  * State Change: DIRTY -> ACTIVE
2061  */
2062 STATIC void
2063 xlog_state_clean_log(xlog_t *log)
2064 {
2065         xlog_in_core_t  *iclog;
2066         int changed = 0;
2067
2068         iclog = log->l_iclog;
2069         do {
2070                 if (iclog->ic_state == XLOG_STATE_DIRTY) {
2071                         iclog->ic_state = XLOG_STATE_ACTIVE;
2072                         iclog->ic_offset       = 0;
2073                         ASSERT(iclog->ic_callback == NULL);
2074                         /*
2075                          * If the number of ops in this iclog indicate it just
2076                          * contains the dummy transaction, we can
2077                          * change state into IDLE (the second time around).
2078                          * Otherwise we should change the state into
2079                          * NEED a dummy.
2080                          * We don't need to cover the dummy.
2081                          */
2082                         if (!changed &&
2083                            (be32_to_cpu(iclog->ic_header.h_num_logops) ==
2084                                         XLOG_COVER_OPS)) {
2085                                 changed = 1;
2086                         } else {
2087                                 /*
2088                                  * We have two dirty iclogs so start over
2089                                  * This could also be num of ops indicates
2090                                  * this is not the dummy going out.
2091                                  */
2092                                 changed = 2;
2093                         }
2094                         iclog->ic_header.h_num_logops = 0;
2095                         memset(iclog->ic_header.h_cycle_data, 0,
2096                               sizeof(iclog->ic_header.h_cycle_data));
2097                         iclog->ic_header.h_lsn = 0;
2098                 } else if (iclog->ic_state == XLOG_STATE_ACTIVE)
2099                         /* do nothing */;
2100                 else
2101                         break;  /* stop cleaning */
2102                 iclog = iclog->ic_next;
2103         } while (iclog != log->l_iclog);
2104
2105         /* log is locked when we are called */
2106         /*
2107          * Change state for the dummy log recording.
2108          * We usually go to NEED. But we go to NEED2 if the changed indicates
2109          * we are done writing the dummy record.
2110          * If we are done with the second dummy recored (DONE2), then
2111          * we go to IDLE.
2112          */
2113         if (changed) {
2114                 switch (log->l_covered_state) {
2115                 case XLOG_STATE_COVER_IDLE:
2116                 case XLOG_STATE_COVER_NEED:
2117                 case XLOG_STATE_COVER_NEED2:
2118                         log->l_covered_state = XLOG_STATE_COVER_NEED;
2119                         break;
2120
2121                 case XLOG_STATE_COVER_DONE:
2122                         if (changed == 1)
2123                                 log->l_covered_state = XLOG_STATE_COVER_NEED2;
2124                         else
2125                                 log->l_covered_state = XLOG_STATE_COVER_NEED;
2126                         break;
2127
2128                 case XLOG_STATE_COVER_DONE2:
2129                         if (changed == 1)
2130                                 log->l_covered_state = XLOG_STATE_COVER_IDLE;
2131                         else
2132                                 log->l_covered_state = XLOG_STATE_COVER_NEED;
2133                         break;
2134
2135                 default:
2136                         ASSERT(0);
2137                 }
2138         }
2139 }       /* xlog_state_clean_log */
2140
2141 STATIC xfs_lsn_t
2142 xlog_get_lowest_lsn(
2143         xlog_t          *log)
2144 {
2145         xlog_in_core_t  *lsn_log;
2146         xfs_lsn_t       lowest_lsn, lsn;
2147
2148         lsn_log = log->l_iclog;
2149         lowest_lsn = 0;
2150         do {
2151             if (!(lsn_log->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY))) {
2152                 lsn = be64_to_cpu(lsn_log->ic_header.h_lsn);
2153                 if ((lsn && !lowest_lsn) ||
2154                     (XFS_LSN_CMP(lsn, lowest_lsn) < 0)) {
2155                         lowest_lsn = lsn;
2156                 }
2157             }
2158             lsn_log = lsn_log->ic_next;
2159         } while (lsn_log != log->l_iclog);
2160         return lowest_lsn;
2161 }
2162
2163
2164 STATIC void
2165 xlog_state_do_callback(
2166         xlog_t          *log,
2167         int             aborted,
2168         xlog_in_core_t  *ciclog)
2169 {
2170         xlog_in_core_t     *iclog;
2171         xlog_in_core_t     *first_iclog;        /* used to know when we've
2172                                                  * processed all iclogs once */
2173         xfs_log_callback_t *cb, *cb_next;
2174         int                flushcnt = 0;
2175         xfs_lsn_t          lowest_lsn;
2176         int                ioerrors;    /* counter: iclogs with errors */
2177         int                loopdidcallbacks; /* flag: inner loop did callbacks*/
2178         int                funcdidcallbacks; /* flag: function did callbacks */
2179         int                repeats;     /* for issuing console warnings if
2180                                          * looping too many times */
2181         int                wake = 0;
2182
2183         spin_lock(&log->l_icloglock);
2184         first_iclog = iclog = log->l_iclog;
2185         ioerrors = 0;
2186         funcdidcallbacks = 0;
2187         repeats = 0;
2188
2189         do {
2190                 /*
2191                  * Scan all iclogs starting with the one pointed to by the
2192                  * log.  Reset this starting point each time the log is
2193                  * unlocked (during callbacks).
2194                  *
2195                  * Keep looping through iclogs until one full pass is made
2196                  * without running any callbacks.
2197                  */
2198                 first_iclog = log->l_iclog;
2199                 iclog = log->l_iclog;
2200                 loopdidcallbacks = 0;
2201                 repeats++;
2202
2203                 do {
2204
2205                         /* skip all iclogs in the ACTIVE & DIRTY states */
2206                         if (iclog->ic_state &
2207                             (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY)) {
2208                                 iclog = iclog->ic_next;
2209                                 continue;
2210                         }
2211
2212                         /*
2213                          * Between marking a filesystem SHUTDOWN and stopping
2214                          * the log, we do flush all iclogs to disk (if there
2215                          * wasn't a log I/O error). So, we do want things to
2216                          * go smoothly in case of just a SHUTDOWN  w/o a
2217                          * LOG_IO_ERROR.
2218                          */
2219                         if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
2220                                 /*
2221                                  * Can only perform callbacks in order.  Since
2222                                  * this iclog is not in the DONE_SYNC/
2223                                  * DO_CALLBACK state, we skip the rest and
2224                                  * just try to clean up.  If we set our iclog
2225                                  * to DO_CALLBACK, we will not process it when
2226                                  * we retry since a previous iclog is in the
2227                                  * CALLBACK and the state cannot change since
2228                                  * we are holding the l_icloglock.
2229                                  */
2230                                 if (!(iclog->ic_state &
2231                                         (XLOG_STATE_DONE_SYNC |
2232                                                  XLOG_STATE_DO_CALLBACK))) {
2233                                         if (ciclog && (ciclog->ic_state ==
2234                                                         XLOG_STATE_DONE_SYNC)) {
2235                                                 ciclog->ic_state = XLOG_STATE_DO_CALLBACK;
2236                                         }
2237                                         break;
2238                                 }
2239                                 /*
2240                                  * We now have an iclog that is in either the
2241                                  * DO_CALLBACK or DONE_SYNC states. The other
2242                                  * states (WANT_SYNC, SYNCING, or CALLBACK were
2243                                  * caught by the above if and are going to
2244                                  * clean (i.e. we aren't doing their callbacks)
2245                                  * see the above if.
2246                                  */
2247
2248                                 /*
2249                                  * We will do one more check here to see if we
2250                                  * have chased our tail around.
2251                                  */
2252
2253                                 lowest_lsn = xlog_get_lowest_lsn(log);
2254                                 if (lowest_lsn &&
2255                                     XFS_LSN_CMP(lowest_lsn,
2256                                                 be64_to_cpu(iclog->ic_header.h_lsn)) < 0) {
2257                                         iclog = iclog->ic_next;
2258                                         continue; /* Leave this iclog for
2259                                                    * another thread */
2260                                 }
2261
2262                                 iclog->ic_state = XLOG_STATE_CALLBACK;
2263
2264                                 spin_unlock(&log->l_icloglock);
2265
2266                                 /* l_last_sync_lsn field protected by
2267                                  * l_grant_lock. Don't worry about iclog's lsn.
2268                                  * No one else can be here except us.
2269                                  */
2270                                 spin_lock(&log->l_grant_lock);
2271                                 ASSERT(XFS_LSN_CMP(log->l_last_sync_lsn,
2272                                        be64_to_cpu(iclog->ic_header.h_lsn)) <= 0);
2273                                 log->l_last_sync_lsn =
2274                                         be64_to_cpu(iclog->ic_header.h_lsn);
2275                                 spin_unlock(&log->l_grant_lock);
2276
2277                         } else {
2278                                 spin_unlock(&log->l_icloglock);
2279                                 ioerrors++;
2280                         }
2281
2282                         /*
2283                          * Keep processing entries in the callback list until
2284                          * we come around and it is empty.  We need to
2285                          * atomically see that the list is empty and change the
2286                          * state to DIRTY so that we don't miss any more
2287                          * callbacks being added.
2288                          */
2289                         spin_lock(&iclog->ic_callback_lock);
2290                         cb = iclog->ic_callback;
2291                         while (cb) {
2292                                 iclog->ic_callback_tail = &(iclog->ic_callback);
2293                                 iclog->ic_callback = NULL;
2294                                 spin_unlock(&iclog->ic_callback_lock);
2295
2296                                 /* perform callbacks in the order given */
2297                                 for (; cb; cb = cb_next) {
2298                                         cb_next = cb->cb_next;
2299                                         cb->cb_func(cb->cb_arg, aborted);
2300                                 }
2301                                 spin_lock(&iclog->ic_callback_lock);
2302                                 cb = iclog->ic_callback;
2303                         }
2304
2305                         loopdidcallbacks++;
2306                         funcdidcallbacks++;
2307
2308                         spin_lock(&log->l_icloglock);
2309                         ASSERT(iclog->ic_callback == NULL);
2310                         spin_unlock(&iclog->ic_callback_lock);
2311                         if (!(iclog->ic_state & XLOG_STATE_IOERROR))
2312                                 iclog->ic_state = XLOG_STATE_DIRTY;
2313
2314                         /*
2315                          * Transition from DIRTY to ACTIVE if applicable.
2316                          * NOP if STATE_IOERROR.
2317                          */
2318                         xlog_state_clean_log(log);
2319
2320                         /* wake up threads waiting in xfs_log_force() */
2321                         sv_broadcast(&iclog->ic_force_wait);
2322
2323                         iclog = iclog->ic_next;
2324                 } while (first_iclog != iclog);
2325
2326                 if (repeats > 5000) {
2327                         flushcnt += repeats;
2328                         repeats = 0;
2329                         xfs_fs_cmn_err(CE_WARN, log->l_mp,
2330                                 "%s: possible infinite loop (%d iterations)",
2331                                 __func__, flushcnt);
2332                 }
2333         } while (!ioerrors && loopdidcallbacks);
2334
2335         /*
2336          * make one last gasp attempt to see if iclogs are being left in
2337          * limbo..
2338          */
2339 #ifdef DEBUG
2340         if (funcdidcallbacks) {
2341                 first_iclog = iclog = log->l_iclog;
2342                 do {
2343                         ASSERT(iclog->ic_state != XLOG_STATE_DO_CALLBACK);
2344                         /*
2345                          * Terminate the loop if iclogs are found in states
2346                          * which will cause other threads to clean up iclogs.
2347                          *
2348                          * SYNCING - i/o completion will go through logs
2349                          * DONE_SYNC - interrupt thread should be waiting for
2350                          *              l_icloglock
2351                          * IOERROR - give up hope all ye who enter here
2352                          */
2353                         if (iclog->ic_state == XLOG_STATE_WANT_SYNC ||
2354                             iclog->ic_state == XLOG_STATE_SYNCING ||
2355                             iclog->ic_state == XLOG_STATE_DONE_SYNC ||
2356                             iclog->ic_state == XLOG_STATE_IOERROR )
2357                                 break;
2358                         iclog = iclog->ic_next;
2359                 } while (first_iclog != iclog);
2360         }
2361 #endif
2362
2363         if (log->l_iclog->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_IOERROR))
2364                 wake = 1;
2365         spin_unlock(&log->l_icloglock);
2366
2367         if (wake)
2368                 sv_broadcast(&log->l_flush_wait);
2369 }
2370
2371
2372 /*
2373  * Finish transitioning this iclog to the dirty state.
2374  *
2375  * Make sure that we completely execute this routine only when this is
2376  * the last call to the iclog.  There is a good chance that iclog flushes,
2377  * when we reach the end of the physical log, get turned into 2 separate
2378  * calls to bwrite.  Hence, one iclog flush could generate two calls to this
2379  * routine.  By using the reference count bwritecnt, we guarantee that only
2380  * the second completion goes through.
2381  *
2382  * Callbacks could take time, so they are done outside the scope of the
2383  * global state machine log lock.
2384  */
2385 STATIC void
2386 xlog_state_done_syncing(
2387         xlog_in_core_t  *iclog,
2388         int             aborted)
2389 {
2390         xlog_t             *log = iclog->ic_log;
2391
2392         spin_lock(&log->l_icloglock);
2393
2394         ASSERT(iclog->ic_state == XLOG_STATE_SYNCING ||
2395                iclog->ic_state == XLOG_STATE_IOERROR);
2396         ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
2397         ASSERT(iclog->ic_bwritecnt == 1 || iclog->ic_bwritecnt == 2);
2398
2399
2400         /*
2401          * If we got an error, either on the first buffer, or in the case of
2402          * split log writes, on the second, we mark ALL iclogs STATE_IOERROR,
2403          * and none should ever be attempted to be written to disk
2404          * again.
2405          */
2406         if (iclog->ic_state != XLOG_STATE_IOERROR) {
2407                 if (--iclog->ic_bwritecnt == 1) {
2408                         spin_unlock(&log->l_icloglock);
2409                         return;
2410                 }
2411                 iclog->ic_state = XLOG_STATE_DONE_SYNC;
2412         }
2413
2414         /*
2415          * Someone could be sleeping prior to writing out the next
2416          * iclog buffer, we wake them all, one will get to do the
2417          * I/O, the others get to wait for the result.
2418          */
2419         sv_broadcast(&iclog->ic_write_wait);
2420         spin_unlock(&log->l_icloglock);
2421         xlog_state_do_callback(log, aborted, iclog);    /* also cleans log */
2422 }       /* xlog_state_done_syncing */
2423
2424
2425 /*
2426  * If the head of the in-core log ring is not (ACTIVE or DIRTY), then we must
2427  * sleep.  We wait on the flush queue on the head iclog as that should be
2428  * the first iclog to complete flushing. Hence if all iclogs are syncing,
2429  * we will wait here and all new writes will sleep until a sync completes.
2430  *
2431  * The in-core logs are used in a circular fashion. They are not used
2432  * out-of-order even when an iclog past the head is free.
2433  *
2434  * return:
2435  *      * log_offset where xlog_write() can start writing into the in-core
2436  *              log's data space.
2437  *      * in-core log pointer to which xlog_write() should write.
2438  *      * boolean indicating this is a continued write to an in-core log.
2439  *              If this is the last write, then the in-core log's offset field
2440  *              needs to be incremented, depending on the amount of data which
2441  *              is copied.
2442  */
2443 STATIC int
2444 xlog_state_get_iclog_space(xlog_t         *log,
2445                            int            len,
2446                            xlog_in_core_t **iclogp,
2447                            xlog_ticket_t  *ticket,
2448                            int            *continued_write,
2449                            int            *logoffsetp)
2450 {
2451         int               log_offset;
2452         xlog_rec_header_t *head;
2453         xlog_in_core_t    *iclog;
2454         int               error;
2455
2456 restart:
2457         spin_lock(&log->l_icloglock);
2458         if (XLOG_FORCED_SHUTDOWN(log)) {
2459                 spin_unlock(&log->l_icloglock);
2460                 return XFS_ERROR(EIO);
2461         }
2462
2463         iclog = log->l_iclog;
2464         if (iclog->ic_state != XLOG_STATE_ACTIVE) {
2465                 XFS_STATS_INC(xs_log_noiclogs);
2466
2467                 /* Wait for log writes to have flushed */
2468                 sv_wait(&log->l_flush_wait, 0, &log->l_icloglock, 0);
2469                 goto restart;
2470         }
2471
2472         head = &iclog->ic_header;
2473
2474         atomic_inc(&iclog->ic_refcnt);  /* prevents sync */
2475         log_offset = iclog->ic_offset;
2476
2477         /* On the 1st write to an iclog, figure out lsn.  This works
2478          * if iclogs marked XLOG_STATE_WANT_SYNC always write out what they are
2479          * committing to.  If the offset is set, that's how many blocks
2480          * must be written.
2481          */
2482         if (log_offset == 0) {
2483                 ticket->t_curr_res -= log->l_iclog_hsize;
2484                 xlog_tic_add_region(ticket,
2485                                     log->l_iclog_hsize,
2486                                     XLOG_REG_TYPE_LRHEADER);
2487                 head->h_cycle = cpu_to_be32(log->l_curr_cycle);
2488                 head->h_lsn = cpu_to_be64(
2489                         xlog_assign_lsn(log->l_curr_cycle, log->l_curr_block));
2490                 ASSERT(log->l_curr_block >= 0);
2491         }
2492
2493         /* If there is enough room to write everything, then do it.  Otherwise,
2494          * claim the rest of the region and make sure the XLOG_STATE_WANT_SYNC
2495          * bit is on, so this will get flushed out.  Don't update ic_offset
2496          * until you know exactly how many bytes get copied.  Therefore, wait
2497          * until later to update ic_offset.
2498          *
2499          * xlog_write() algorithm assumes that at least 2 xlog_op_header_t's
2500          * can fit into remaining data section.
2501          */
2502         if (iclog->ic_size - iclog->ic_offset < 2*sizeof(xlog_op_header_t)) {
2503                 xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2504
2505                 /*
2506                  * If I'm the only one writing to this iclog, sync it to disk.
2507                  * We need to do an atomic compare and decrement here to avoid
2508                  * racing with concurrent atomic_dec_and_lock() calls in
2509                  * xlog_state_release_iclog() when there is more than one
2510                  * reference to the iclog.
2511                  */
2512                 if (!atomic_add_unless(&iclog->ic_refcnt, -1, 1)) {
2513                         /* we are the only one */
2514                         spin_unlock(&log->l_icloglock);
2515                         error = xlog_state_release_iclog(log, iclog);
2516                         if (error)
2517                                 return error;
2518                 } else {
2519                         spin_unlock(&log->l_icloglock);
2520                 }
2521                 goto restart;
2522         }
2523
2524         /* Do we have enough room to write the full amount in the remainder
2525          * of this iclog?  Or must we continue a write on the next iclog and
2526          * mark this iclog as completely taken?  In the case where we switch
2527          * iclogs (to mark it taken), this particular iclog will release/sync
2528          * to disk in xlog_write().
2529          */
2530         if (len <= iclog->ic_size - iclog->ic_offset) {
2531                 *continued_write = 0;
2532                 iclog->ic_offset += len;
2533         } else {
2534                 *continued_write = 1;
2535                 xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2536         }
2537         *iclogp = iclog;
2538
2539         ASSERT(iclog->ic_offset <= iclog->ic_size);
2540         spin_unlock(&log->l_icloglock);
2541
2542         *logoffsetp = log_offset;
2543         return 0;
2544 }       /* xlog_state_get_iclog_space */
2545
2546 /*
2547  * Atomically get the log space required for a log ticket.
2548  *
2549  * Once a ticket gets put onto the reserveq, it will only return after
2550  * the needed reservation is satisfied.
2551  */
2552 STATIC int
2553 xlog_grant_log_space(xlog_t        *log,
2554                      xlog_ticket_t *tic)
2555 {
2556         int              free_bytes;
2557         int              need_bytes;
2558 #ifdef DEBUG
2559         xfs_lsn_t        tail_lsn;
2560 #endif
2561
2562
2563 #ifdef DEBUG
2564         if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2565                 panic("grant Recovery problem");
2566 #endif
2567
2568         /* Is there space or do we need to sleep? */
2569         spin_lock(&log->l_grant_lock);
2570
2571         trace_xfs_log_grant_enter(log, tic);
2572
2573         /* something is already sleeping; insert new transaction at end */
2574         if (log->l_reserve_headq) {
2575                 xlog_ins_ticketq(&log->l_reserve_headq, tic);
2576
2577                 trace_xfs_log_grant_sleep1(log, tic);
2578
2579                 /*
2580                  * Gotta check this before going to sleep, while we're
2581                  * holding the grant lock.
2582                  */
2583                 if (XLOG_FORCED_SHUTDOWN(log))
2584                         goto error_return;
2585
2586                 XFS_STATS_INC(xs_sleep_logspace);
2587                 sv_wait(&tic->t_wait, PINOD|PLTWAIT, &log->l_grant_lock, s);
2588                 /*
2589                  * If we got an error, and the filesystem is shutting down,
2590                  * we'll catch it down below. So just continue...
2591                  */
2592                 trace_xfs_log_grant_wake1(log, tic);
2593                 spin_lock(&log->l_grant_lock);
2594         }
2595         if (tic->t_flags & XFS_LOG_PERM_RESERV)
2596                 need_bytes = tic->t_unit_res*tic->t_ocnt;
2597         else
2598                 need_bytes = tic->t_unit_res;
2599
2600 redo:
2601         if (XLOG_FORCED_SHUTDOWN(log))
2602                 goto error_return;
2603
2604         free_bytes = xlog_space_left(log, log->l_grant_reserve_cycle,
2605                                      log->l_grant_reserve_bytes);
2606         if (free_bytes < need_bytes) {
2607                 if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2608                         xlog_ins_ticketq(&log->l_reserve_headq, tic);
2609
2610                 trace_xfs_log_grant_sleep2(log, tic);
2611
2612                 spin_unlock(&log->l_grant_lock);
2613                 xlog_grant_push_ail(log->l_mp, need_bytes);
2614                 spin_lock(&log->l_grant_lock);
2615
2616                 XFS_STATS_INC(xs_sleep_logspace);
2617                 sv_wait(&tic->t_wait, PINOD|PLTWAIT, &log->l_grant_lock, s);
2618
2619                 spin_lock(&log->l_grant_lock);
2620                 if (XLOG_FORCED_SHUTDOWN(log))
2621                         goto error_return;
2622
2623                 trace_xfs_log_grant_wake2(log, tic);
2624
2625                 goto redo;
2626         } else if (tic->t_flags & XLOG_TIC_IN_Q)
2627                 xlog_del_ticketq(&log->l_reserve_headq, tic);
2628
2629         /* we've got enough space */
2630         xlog_grant_add_space(log, need_bytes);
2631 #ifdef DEBUG
2632         tail_lsn = log->l_tail_lsn;
2633         /*
2634          * Check to make sure the grant write head didn't just over lap the
2635          * tail.  If the cycles are the same, we can't be overlapping.
2636          * Otherwise, make sure that the cycles differ by exactly one and
2637          * check the byte count.
2638          */
2639         if (CYCLE_LSN(tail_lsn) != log->l_grant_write_cycle) {
2640                 ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn));
2641                 ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn)));
2642         }
2643 #endif
2644         trace_xfs_log_grant_exit(log, tic);
2645         xlog_verify_grant_head(log, 1);
2646         spin_unlock(&log->l_grant_lock);
2647         return 0;
2648
2649  error_return:
2650         if (tic->t_flags & XLOG_TIC_IN_Q)
2651                 xlog_del_ticketq(&log->l_reserve_headq, tic);
2652
2653         trace_xfs_log_grant_error(log, tic);
2654
2655         /*
2656          * If we are failing, make sure the ticket doesn't have any
2657          * current reservations. We don't want to add this back when
2658          * the ticket/transaction gets cancelled.
2659          */
2660         tic->t_curr_res = 0;
2661         tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2662         spin_unlock(&log->l_grant_lock);
2663         return XFS_ERROR(EIO);
2664 }       /* xlog_grant_log_space */
2665
2666
2667 /*
2668  * Replenish the byte reservation required by moving the grant write head.
2669  *
2670  *
2671  */
2672 STATIC int
2673 xlog_regrant_write_log_space(xlog_t        *log,
2674                              xlog_ticket_t *tic)
2675 {
2676         int             free_bytes, need_bytes;
2677         xlog_ticket_t   *ntic;
2678 #ifdef DEBUG
2679         xfs_lsn_t       tail_lsn;
2680 #endif
2681
2682         tic->t_curr_res = tic->t_unit_res;
2683         xlog_tic_reset_res(tic);
2684
2685         if (tic->t_cnt > 0)
2686                 return 0;
2687
2688 #ifdef DEBUG
2689         if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2690                 panic("regrant Recovery problem");
2691 #endif
2692
2693         spin_lock(&log->l_grant_lock);
2694
2695         trace_xfs_log_regrant_write_enter(log, tic);
2696
2697         if (XLOG_FORCED_SHUTDOWN(log))
2698                 goto error_return;
2699
2700         /* If there are other waiters on the queue then give them a
2701          * chance at logspace before us. Wake up the first waiters,
2702          * if we do not wake up all the waiters then go to sleep waiting
2703          * for more free space, otherwise try to get some space for
2704          * this transaction.
2705          */
2706         need_bytes = tic->t_unit_res;
2707         if ((ntic = log->l_write_headq)) {
2708                 free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2709                                              log->l_grant_write_bytes);
2710                 do {
2711                         ASSERT(ntic->t_flags & XLOG_TIC_PERM_RESERV);
2712
2713                         if (free_bytes < ntic->t_unit_res)
2714                                 break;
2715                         free_bytes -= ntic->t_unit_res;
2716                         sv_signal(&ntic->t_wait);
2717                         ntic = ntic->t_next;
2718                 } while (ntic != log->l_write_headq);
2719
2720                 if (ntic != log->l_write_headq) {
2721                         if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2722                                 xlog_ins_ticketq(&log->l_write_headq, tic);
2723
2724                         trace_xfs_log_regrant_write_sleep1(log, tic);
2725
2726                         spin_unlock(&log->l_grant_lock);
2727                         xlog_grant_push_ail(log->l_mp, need_bytes);
2728                         spin_lock(&log->l_grant_lock);
2729
2730                         XFS_STATS_INC(xs_sleep_logspace);
2731                         sv_wait(&tic->t_wait, PINOD|PLTWAIT,
2732                                 &log->l_grant_lock, s);
2733
2734                         /* If we're shutting down, this tic is already
2735                          * off the queue */
2736                         spin_lock(&log->l_grant_lock);
2737                         if (XLOG_FORCED_SHUTDOWN(log))
2738                                 goto error_return;
2739
2740                         trace_xfs_log_regrant_write_wake1(log, tic);
2741                 }
2742         }
2743
2744 redo:
2745         if (XLOG_FORCED_SHUTDOWN(log))
2746                 goto error_return;
2747
2748         free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2749                                      log->l_grant_write_bytes);
2750         if (free_bytes < need_bytes) {
2751                 if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2752                         xlog_ins_ticketq(&log->l_write_headq, tic);
2753                 spin_unlock(&log->l_grant_lock);
2754                 xlog_grant_push_ail(log->l_mp, need_bytes);
2755                 spin_lock(&log->l_grant_lock);
2756
2757                 XFS_STATS_INC(xs_sleep_logspace);
2758                 trace_xfs_log_regrant_write_sleep2(log, tic);
2759
2760                 sv_wait(&tic->t_wait, PINOD|PLTWAIT, &log->l_grant_lock, s);
2761
2762                 /* If we're shutting down, this tic is already off the queue */
2763                 spin_lock(&log->l_grant_lock);
2764                 if (XLOG_FORCED_SHUTDOWN(log))
2765                         goto error_return;
2766
2767                 trace_xfs_log_regrant_write_wake2(log, tic);
2768                 goto redo;
2769         } else if (tic->t_flags & XLOG_TIC_IN_Q)
2770                 xlog_del_ticketq(&log->l_write_headq, tic);
2771
2772         /* we've got enough space */
2773         xlog_grant_add_space_write(log, need_bytes);
2774 #ifdef DEBUG
2775         tail_lsn = log->l_tail_lsn;
2776         if (CYCLE_LSN(tail_lsn) != log->l_grant_write_cycle) {
2777                 ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn));
2778                 ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn)));
2779         }
2780 #endif
2781
2782         trace_xfs_log_regrant_write_exit(log, tic);
2783
2784         xlog_verify_grant_head(log, 1);
2785         spin_unlock(&log->l_grant_lock);
2786         return 0;
2787
2788
2789  error_return:
2790         if (tic->t_flags & XLOG_TIC_IN_Q)
2791                 xlog_del_ticketq(&log->l_reserve_headq, tic);
2792
2793         trace_xfs_log_regrant_write_error(log, tic);
2794
2795         /*
2796          * If we are failing, make sure the ticket doesn't have any
2797          * current reservations. We don't want to add this back when
2798          * the ticket/transaction gets cancelled.
2799          */
2800         tic->t_curr_res = 0;
2801         tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2802         spin_unlock(&log->l_grant_lock);
2803         return XFS_ERROR(EIO);
2804 }       /* xlog_regrant_write_log_space */
2805
2806
2807 /* The first cnt-1 times through here we don't need to
2808  * move the grant write head because the permanent
2809  * reservation has reserved cnt times the unit amount.
2810  * Release part of current permanent unit reservation and
2811  * reset current reservation to be one units worth.  Also
2812  * move grant reservation head forward.
2813  */
2814 STATIC void
2815 xlog_regrant_reserve_log_space(xlog_t        *log,
2816                                xlog_ticket_t *ticket)
2817 {
2818         trace_xfs_log_regrant_reserve_enter(log, ticket);
2819
2820         if (ticket->t_cnt > 0)
2821                 ticket->t_cnt--;
2822
2823         spin_lock(&log->l_grant_lock);
2824         xlog_grant_sub_space(log, ticket->t_curr_res);
2825         ticket->t_curr_res = ticket->t_unit_res;
2826         xlog_tic_reset_res(ticket);
2827
2828         trace_xfs_log_regrant_reserve_sub(log, ticket);
2829
2830         xlog_verify_grant_head(log, 1);
2831
2832         /* just return if we still have some of the pre-reserved space */
2833         if (ticket->t_cnt > 0) {
2834                 spin_unlock(&log->l_grant_lock);
2835                 return;
2836         }
2837
2838         xlog_grant_add_space_reserve(log, ticket->t_unit_res);
2839
2840         trace_xfs_log_regrant_reserve_exit(log, ticket);
2841
2842         xlog_verify_grant_head(log, 0);
2843         spin_unlock(&log->l_grant_lock);
2844         ticket->t_curr_res = ticket->t_unit_res;
2845         xlog_tic_reset_res(ticket);
2846 }       /* xlog_regrant_reserve_log_space */
2847
2848
2849 /*
2850  * Give back the space left from a reservation.
2851  *
2852  * All the information we need to make a correct determination of space left
2853  * is present.  For non-permanent reservations, things are quite easy.  The
2854  * count should have been decremented to zero.  We only need to deal with the
2855  * space remaining in the current reservation part of the ticket.  If the
2856  * ticket contains a permanent reservation, there may be left over space which
2857  * needs to be released.  A count of N means that N-1 refills of the current
2858  * reservation can be done before we need to ask for more space.  The first
2859  * one goes to fill up the first current reservation.  Once we run out of
2860  * space, the count will stay at zero and the only space remaining will be
2861  * in the current reservation field.
2862  */
2863 STATIC void
2864 xlog_ungrant_log_space(xlog_t        *log,
2865                        xlog_ticket_t *ticket)
2866 {
2867         if (ticket->t_cnt > 0)
2868                 ticket->t_cnt--;
2869
2870         spin_lock(&log->l_grant_lock);
2871         trace_xfs_log_ungrant_enter(log, ticket);
2872
2873         xlog_grant_sub_space(log, ticket->t_curr_res);
2874
2875         trace_xfs_log_ungrant_sub(log, ticket);
2876
2877         /* If this is a permanent reservation ticket, we may be able to free
2878          * up more space based on the remaining count.
2879          */
2880         if (ticket->t_cnt > 0) {
2881                 ASSERT(ticket->t_flags & XLOG_TIC_PERM_RESERV);
2882                 xlog_grant_sub_space(log, ticket->t_unit_res*ticket->t_cnt);
2883         }
2884
2885         trace_xfs_log_ungrant_exit(log, ticket);
2886
2887         xlog_verify_grant_head(log, 1);
2888         spin_unlock(&log->l_grant_lock);
2889         xfs_log_move_tail(log->l_mp, 1);
2890 }       /* xlog_ungrant_log_space */
2891
2892
2893 /*
2894  * Flush iclog to disk if this is the last reference to the given iclog and
2895  * the WANT_SYNC bit is set.
2896  *
2897  * When this function is entered, the iclog is not necessarily in the
2898  * WANT_SYNC state.  It may be sitting around waiting to get filled.
2899  *
2900  *
2901  */
2902 STATIC int
2903 xlog_state_release_iclog(
2904         xlog_t          *log,
2905         xlog_in_core_t  *iclog)
2906 {
2907         int             sync = 0;       /* do we sync? */
2908
2909         if (iclog->ic_state & XLOG_STATE_IOERROR)
2910                 return XFS_ERROR(EIO);
2911
2912         ASSERT(atomic_read(&iclog->ic_refcnt) > 0);
2913         if (!atomic_dec_and_lock(&iclog->ic_refcnt, &log->l_icloglock))
2914                 return 0;
2915
2916         if (iclog->ic_state & XLOG_STATE_IOERROR) {
2917                 spin_unlock(&log->l_icloglock);
2918                 return XFS_ERROR(EIO);
2919         }
2920         ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE ||
2921                iclog->ic_state == XLOG_STATE_WANT_SYNC);
2922
2923         if (iclog->ic_state == XLOG_STATE_WANT_SYNC) {
2924                 /* update tail before writing to iclog */
2925                 xlog_assign_tail_lsn(log->l_mp);
2926                 sync++;
2927                 iclog->ic_state = XLOG_STATE_SYNCING;
2928                 iclog->ic_header.h_tail_lsn = cpu_to_be64(log->l_tail_lsn);
2929                 xlog_verify_tail_lsn(log, iclog, log->l_tail_lsn);
2930                 /* cycle incremented when incrementing curr_block */
2931         }
2932         spin_unlock(&log->l_icloglock);
2933
2934         /*
2935          * We let the log lock go, so it's possible that we hit a log I/O
2936          * error or some other SHUTDOWN condition that marks the iclog
2937          * as XLOG_STATE_IOERROR before the bwrite. However, we know that
2938          * this iclog has consistent data, so we ignore IOERROR
2939          * flags after this point.
2940          */
2941         if (sync)
2942                 return xlog_sync(log, iclog);
2943         return 0;
2944 }       /* xlog_state_release_iclog */
2945
2946
2947 /*
2948  * This routine will mark the current iclog in the ring as WANT_SYNC
2949  * and move the current iclog pointer to the next iclog in the ring.
2950  * When this routine is called from xlog_state_get_iclog_space(), the
2951  * exact size of the iclog has not yet been determined.  All we know is
2952  * that every data block.  We have run out of space in this log record.
2953  */
2954 STATIC void
2955 xlog_state_switch_iclogs(xlog_t         *log,
2956                          xlog_in_core_t *iclog,
2957                          int            eventual_size)
2958 {
2959         ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
2960         if (!eventual_size)
2961                 eventual_size = iclog->ic_offset;
2962         iclog->ic_state = XLOG_STATE_WANT_SYNC;
2963         iclog->ic_header.h_prev_block = cpu_to_be32(log->l_prev_block);
2964         log->l_prev_block = log->l_curr_block;
2965         log->l_prev_cycle = log->l_curr_cycle;
2966
2967         /* roll log?: ic_offset changed later */
2968         log->l_curr_block += BTOBB(eventual_size)+BTOBB(log->l_iclog_hsize);
2969
2970         /* Round up to next log-sunit */
2971         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb) &&
2972             log->l_mp->m_sb.sb_logsunit > 1) {
2973                 __uint32_t sunit_bb = BTOBB(log->l_mp->m_sb.sb_logsunit);
2974                 log->l_curr_block = roundup(log->l_curr_block, sunit_bb);
2975         }
2976
2977         if (log->l_curr_block >= log->l_logBBsize) {
2978                 log->l_curr_cycle++;
2979                 if (log->l_curr_cycle == XLOG_HEADER_MAGIC_NUM)
2980                         log->l_curr_cycle++;
2981                 log->l_curr_block -= log->l_logBBsize;
2982                 ASSERT(log->l_curr_block >= 0);
2983         }
2984         ASSERT(iclog == log->l_iclog);
2985         log->l_iclog = iclog->ic_next;
2986 }       /* xlog_state_switch_iclogs */
2987
2988 /*
2989  * Write out all data in the in-core log as of this exact moment in time.
2990  *
2991  * Data may be written to the in-core log during this call.  However,
2992  * we don't guarantee this data will be written out.  A change from past
2993  * implementation means this routine will *not* write out zero length LRs.
2994  *
2995  * Basically, we try and perform an intelligent scan of the in-core logs.
2996  * If we determine there is no flushable data, we just return.  There is no
2997  * flushable data if:
2998  *
2999  *      1. the current iclog is active and has no data; the previous iclog
3000  *              is in the active or dirty state.
3001  *      2. the current iclog is drity, and the previous iclog is in the
3002  *              active or dirty state.
3003  *
3004  * We may sleep if:
3005  *
3006  *      1. the current iclog is not in the active nor dirty state.
3007  *      2. the current iclog dirty, and the previous iclog is not in the
3008  *              active nor dirty state.
3009  *      3. the current iclog is active, and there is another thread writing
3010  *              to this particular iclog.
3011  *      4. a) the current iclog is active and has no other writers
3012  *         b) when we return from flushing out this iclog, it is still
3013  *              not in the active nor dirty state.
3014  */
3015 int
3016 _xfs_log_force(
3017         struct xfs_mount        *mp,
3018         uint                    flags,
3019         int                     *log_flushed)
3020 {
3021         struct log              *log = mp->m_log;
3022         struct xlog_in_core     *iclog;
3023         xfs_lsn_t               lsn;
3024
3025         XFS_STATS_INC(xs_log_force);
3026
3027         xlog_cil_push(log, 1);
3028
3029         spin_lock(&log->l_icloglock);
3030
3031         iclog = log->l_iclog;
3032         if (iclog->ic_state & XLOG_STATE_IOERROR) {
3033                 spin_unlock(&log->l_icloglock);
3034                 return XFS_ERROR(EIO);
3035         }
3036
3037         /* If the head iclog is not active nor dirty, we just attach
3038          * ourselves to the head and go to sleep.
3039          */
3040         if (iclog->ic_state == XLOG_STATE_ACTIVE ||
3041             iclog->ic_state == XLOG_STATE_DIRTY) {
3042                 /*
3043                  * If the head is dirty or (active and empty), then
3044                  * we need to look at the previous iclog.  If the previous
3045                  * iclog is active or dirty we are done.  There is nothing
3046                  * to sync out.  Otherwise, we attach ourselves to the
3047                  * previous iclog and go to sleep.
3048                  */
3049                 if (iclog->ic_state == XLOG_STATE_DIRTY ||
3050                     (atomic_read(&iclog->ic_refcnt) == 0
3051                      && iclog->ic_offset == 0)) {
3052                         iclog = iclog->ic_prev;
3053                         if (iclog->ic_state == XLOG_STATE_ACTIVE ||
3054                             iclog->ic_state == XLOG_STATE_DIRTY)
3055                                 goto no_sleep;
3056                         else
3057                                 goto maybe_sleep;
3058                 } else {
3059                         if (atomic_read(&iclog->ic_refcnt) == 0) {
3060                                 /* We are the only one with access to this
3061                                  * iclog.  Flush it out now.  There should
3062                                  * be a roundoff of zero to show that someone
3063                                  * has already taken care of the roundoff from
3064                                  * the previous sync.
3065                                  */
3066                                 atomic_inc(&iclog->ic_refcnt);
3067                                 lsn = be64_to_cpu(iclog->ic_header.h_lsn);
3068                                 xlog_state_switch_iclogs(log, iclog, 0);
3069                                 spin_unlock(&log->l_icloglock);
3070
3071                                 if (xlog_state_release_iclog(log, iclog))
3072                                         return XFS_ERROR(EIO);
3073
3074                                 if (log_flushed)
3075                                         *log_flushed = 1;
3076                                 spin_lock(&log->l_icloglock);
3077                                 if (be64_to_cpu(iclog->ic_header.h_lsn) == lsn &&
3078                                     iclog->ic_state != XLOG_STATE_DIRTY)
3079                                         goto maybe_sleep;
3080                                 else
3081                                         goto no_sleep;
3082                         } else {
3083                                 /* Someone else is writing to this iclog.
3084                                  * Use its call to flush out the data.  However,
3085                                  * the other thread may not force out this LR,
3086                                  * so we mark it WANT_SYNC.
3087                                  */
3088                                 xlog_state_switch_iclogs(log, iclog, 0);
3089                                 goto maybe_sleep;
3090                         }
3091                 }
3092         }
3093
3094         /* By the time we come around again, the iclog could've been filled
3095          * which would give it another lsn.  If we have a new lsn, just
3096          * return because the relevant data has been flushed.
3097          */
3098 maybe_sleep:
3099         if (flags & XFS_LOG_SYNC) {
3100                 /*
3101                  * We must check if we're shutting down here, before
3102                  * we wait, while we're holding the l_icloglock.
3103                  * Then we check again after waking up, in case our
3104                  * sleep was disturbed by a bad news.
3105                  */
3106                 if (iclog->ic_state & XLOG_STATE_IOERROR) {
3107                         spin_unlock(&log->l_icloglock);
3108                         return XFS_ERROR(EIO);
3109                 }
3110                 XFS_STATS_INC(xs_log_force_sleep);
3111                 sv_wait(&iclog->ic_force_wait, PINOD, &log->l_icloglock, s);
3112                 /*
3113                  * No need to grab the log lock here since we're
3114                  * only deciding whether or not to return EIO
3115                  * and the memory read should be atomic.
3116                  */
3117                 if (iclog->ic_state & XLOG_STATE_IOERROR)
3118                         return XFS_ERROR(EIO);
3119                 if (log_flushed)
3120                         *log_flushed = 1;
3121         } else {
3122
3123 no_sleep:
3124                 spin_unlock(&log->l_icloglock);
3125         }
3126         return 0;
3127 }
3128
3129 /*
3130  * Wrapper for _xfs_log_force(), to be used when caller doesn't care
3131  * about errors or whether the log was flushed or not. This is the normal
3132  * interface to use when trying to unpin items or move the log forward.
3133  */
3134 void
3135 xfs_log_force(
3136         xfs_mount_t     *mp,
3137         uint            flags)
3138 {
3139         int     error;
3140
3141         error = _xfs_log_force(mp, flags, NULL);
3142         if (error) {
3143                 xfs_fs_cmn_err(CE_WARN, mp, "xfs_log_force: "
3144                         "error %d returned.", error);
3145         }
3146 }
3147
3148 /*
3149  * Force the in-core log to disk for a specific LSN.
3150  *
3151  * Find in-core log with lsn.
3152  *      If it is in the DIRTY state, just return.
3153  *      If it is in the ACTIVE state, move the in-core log into the WANT_SYNC
3154  *              state and go to sleep or return.
3155  *      If it is in any other state, go to sleep or return.
3156  *
3157  * Synchronous forces are implemented with a signal variable. All callers
3158  * to force a given lsn to disk will wait on a the sv attached to the
3159  * specific in-core log.  When given in-core log finally completes its
3160  * write to disk, that thread will wake up all threads waiting on the
3161  * sv.
3162  */
3163 int
3164 _xfs_log_force_lsn(
3165         struct xfs_mount        *mp,
3166         xfs_lsn_t               lsn,
3167         uint                    flags,
3168         int                     *log_flushed)
3169 {
3170         struct log              *log = mp->m_log;
3171         struct xlog_in_core     *iclog;
3172         int                     already_slept = 0;
3173
3174         ASSERT(lsn != 0);
3175
3176         XFS_STATS_INC(xs_log_force);
3177
3178         if (log->l_cilp) {
3179                 lsn = xlog_cil_push_lsn(log, lsn);
3180                 if (lsn == NULLCOMMITLSN)
3181                         return 0;
3182         }
3183
3184 try_again:
3185         spin_lock(&log->l_icloglock);
3186         iclog = log->l_iclog;
3187         if (iclog->ic_state & XLOG_STATE_IOERROR) {
3188                 spin_unlock(&log->l_icloglock);
3189                 return XFS_ERROR(EIO);
3190         }
3191
3192         do {
3193                 if (be64_to_cpu(iclog->ic_header.h_lsn) != lsn) {
3194                         iclog = iclog->ic_next;
3195                         continue;
3196                 }
3197
3198                 if (iclog->ic_state == XLOG_STATE_DIRTY) {
3199                         spin_unlock(&log->l_icloglock);
3200                         return 0;
3201                 }
3202
3203                 if (iclog->ic_state == XLOG_STATE_ACTIVE) {
3204                         /*
3205                          * We sleep here if we haven't already slept (e.g.
3206                          * this is the first time we've looked at the correct
3207                          * iclog buf) and the buffer before us is going to
3208                          * be sync'ed. The reason for this is that if we
3209                          * are doing sync transactions here, by waiting for
3210                          * the previous I/O to complete, we can allow a few
3211                          * more transactions into this iclog before we close
3212                          * it down.
3213                          *
3214                          * Otherwise, we mark the buffer WANT_SYNC, and bump
3215                          * up the refcnt so we can release the log (which
3216                          * drops the ref count).  The state switch keeps new
3217                          * transaction commits from using this buffer.  When
3218                          * the current commits finish writing into the buffer,
3219                          * the refcount will drop to zero and the buffer will
3220                          * go out then.
3221                          */
3222                         if (!already_slept &&
3223                             (iclog->ic_prev->ic_state &
3224                              (XLOG_STATE_WANT_SYNC | XLOG_STATE_SYNCING))) {
3225                                 ASSERT(!(iclog->ic_state & XLOG_STATE_IOERROR));
3226
3227                                 XFS_STATS_INC(xs_log_force_sleep);
3228
3229                                 sv_wait(&iclog->ic_prev->ic_write_wait,
3230                                         PSWP, &log->l_icloglock, s);
3231                                 if (log_flushed)
3232                                         *log_flushed = 1;
3233                                 already_slept = 1;
3234                                 goto try_again;
3235                         }
3236                         atomic_inc(&iclog->ic_refcnt);
3237                         xlog_state_switch_iclogs(log, iclog, 0);
3238                         spin_unlock(&log->l_icloglock);
3239                         if (xlog_state_release_iclog(log, iclog))
3240                                 return XFS_ERROR(EIO);
3241                         if (log_flushed)
3242                                 *log_flushed = 1;
3243                         spin_lock(&log->l_icloglock);
3244                 }
3245
3246                 if ((flags & XFS_LOG_SYNC) && /* sleep */
3247                     !(iclog->ic_state &
3248                       (XLOG_STATE_ACTIVE | XLOG_STATE_DIRTY))) {
3249                         /*
3250                          * Don't wait on completion if we know that we've
3251                          * gotten a log write error.
3252                          */
3253                         if (iclog->ic_state & XLOG_STATE_IOERROR) {
3254                                 spin_unlock(&log->l_icloglock);
3255                                 return XFS_ERROR(EIO);
3256                         }
3257                         XFS_STATS_INC(xs_log_force_sleep);
3258                         sv_wait(&iclog->ic_force_wait, PSWP, &log->l_icloglock, s);
3259                         /*
3260                          * No need to grab the log lock here since we're
3261                          * only deciding whether or not to return EIO
3262                          * and the memory read should be atomic.
3263                          */
3264                         if (iclog->ic_state & XLOG_STATE_IOERROR)
3265                                 return XFS_ERROR(EIO);
3266
3267                         if (log_flushed)
3268                                 *log_flushed = 1;
3269                 } else {                /* just return */
3270                         spin_unlock(&log->l_icloglock);
3271                 }
3272
3273                 return 0;
3274         } while (iclog != log->l_iclog);
3275
3276         spin_unlock(&log->l_icloglock);
3277         return 0;
3278 }
3279
3280 /*
3281  * Wrapper for _xfs_log_force_lsn(), to be used when caller doesn't care
3282  * about errors or whether the log was flushed or not. This is the normal
3283  * interface to use when trying to unpin items or move the log forward.
3284  */
3285 void
3286 xfs_log_force_lsn(
3287         xfs_mount_t     *mp,
3288         xfs_lsn_t       lsn,
3289         uint            flags)
3290 {
3291         int     error;
3292
3293         error = _xfs_log_force_lsn(mp, lsn, flags, NULL);
3294         if (error) {
3295                 xfs_fs_cmn_err(CE_WARN, mp, "xfs_log_force: "
3296                         "error %d returned.", error);
3297         }
3298 }
3299
3300 /*
3301  * Called when we want to mark the current iclog as being ready to sync to
3302  * disk.
3303  */
3304 STATIC void
3305 xlog_state_want_sync(xlog_t *log, xlog_in_core_t *iclog)
3306 {
3307         assert_spin_locked(&log->l_icloglock);
3308
3309         if (iclog->ic_state == XLOG_STATE_ACTIVE) {
3310                 xlog_state_switch_iclogs(log, iclog, 0);
3311         } else {
3312                 ASSERT(iclog->ic_state &
3313                         (XLOG_STATE_WANT_SYNC|XLOG_STATE_IOERROR));
3314         }
3315 }
3316
3317
3318 /*****************************************************************************
3319  *
3320  *              TICKET functions
3321  *
3322  *****************************************************************************
3323  */
3324
3325 /*
3326  * Free a used ticket when its refcount falls to zero.
3327  */
3328 void
3329 xfs_log_ticket_put(
3330         xlog_ticket_t   *ticket)
3331 {
3332         ASSERT(atomic_read(&ticket->t_ref) > 0);
3333         if (atomic_dec_and_test(&ticket->t_ref)) {
3334                 sv_destroy(&ticket->t_wait);
3335                 kmem_zone_free(xfs_log_ticket_zone, ticket);
3336         }
3337 }
3338
3339 xlog_ticket_t *
3340 xfs_log_ticket_get(
3341         xlog_ticket_t   *ticket)
3342 {
3343         ASSERT(atomic_read(&ticket->t_ref) > 0);
3344         atomic_inc(&ticket->t_ref);
3345         return ticket;
3346 }
3347
3348 xlog_tid_t
3349 xfs_log_get_trans_ident(
3350         struct xfs_trans        *tp)
3351 {
3352         return tp->t_ticket->t_tid;
3353 }
3354
3355 /*
3356  * Allocate and initialise a new log ticket.
3357  */
3358 xlog_ticket_t *
3359 xlog_ticket_alloc(
3360         struct log      *log,
3361         int             unit_bytes,
3362         int             cnt,
3363         char            client,
3364         uint            xflags,
3365         int             alloc_flags)
3366 {
3367         struct xlog_ticket *tic;
3368         uint            num_headers;
3369         int             iclog_space;
3370
3371         tic = kmem_zone_zalloc(xfs_log_ticket_zone, alloc_flags);
3372         if (!tic)
3373                 return NULL;
3374
3375         /*
3376          * Permanent reservations have up to 'cnt'-1 active log operations
3377          * in the log.  A unit in this case is the amount of space for one
3378          * of these log operations.  Normal reservations have a cnt of 1
3379          * and their unit amount is the total amount of space required.
3380          *
3381          * The following lines of code account for non-transaction data
3382          * which occupy space in the on-disk log.
3383          *
3384          * Normal form of a transaction is:
3385          * <oph><trans-hdr><start-oph><reg1-oph><reg1><reg2-oph>...<commit-oph>
3386          * and then there are LR hdrs, split-recs and roundoff at end of syncs.
3387          *
3388          * We need to account for all the leadup data and trailer data
3389          * around the transaction data.
3390          * And then we need to account for the worst case in terms of using
3391          * more space.
3392          * The worst case will happen if:
3393          * - the placement of the transaction happens to be such that the
3394          *   roundoff is at its maximum
3395          * - the transaction data is synced before the commit record is synced
3396          *   i.e. <transaction-data><roundoff> | <commit-rec><roundoff>
3397          *   Therefore the commit record is in its own Log Record.
3398          *   This can happen as the commit record is called with its
3399          *   own region to xlog_write().
3400          *   This then means that in the worst case, roundoff can happen for
3401          *   the commit-rec as well.
3402          *   The commit-rec is smaller than padding in this scenario and so it is
3403          *   not added separately.
3404          */
3405
3406         /* for trans header */
3407         unit_bytes += sizeof(xlog_op_header_t);
3408         unit_bytes += sizeof(xfs_trans_header_t);
3409
3410         /* for start-rec */
3411         unit_bytes += sizeof(xlog_op_header_t);
3412
3413         /*
3414          * for LR headers - the space for data in an iclog is the size minus
3415          * the space used for the headers. If we use the iclog size, then we
3416          * undercalculate the number of headers required.
3417          *
3418          * Furthermore - the addition of op headers for split-recs might
3419          * increase the space required enough to require more log and op
3420          * headers, so take that into account too.
3421          *
3422          * IMPORTANT: This reservation makes the assumption that if this
3423          * transaction is the first in an iclog and hence has the LR headers
3424          * accounted to it, then the remaining space in the iclog is
3425          * exclusively for this transaction.  i.e. if the transaction is larger
3426          * than the iclog, it will be the only thing in that iclog.
3427          * Fundamentally, this means we must pass the entire log vector to
3428          * xlog_write to guarantee this.
3429          */
3430         iclog_space = log->l_iclog_size - log->l_iclog_hsize;
3431         num_headers = howmany(unit_bytes, iclog_space);
3432
3433         /* for split-recs - ophdrs added when data split over LRs */
3434         unit_bytes += sizeof(xlog_op_header_t) * num_headers;
3435
3436         /* add extra header reservations if we overrun */
3437         while (!num_headers ||
3438                howmany(unit_bytes, iclog_space) > num_headers) {
3439                 unit_bytes += sizeof(xlog_op_header_t);
3440                 num_headers++;
3441         }
3442         unit_bytes += log->l_iclog_hsize * num_headers;
3443
3444         /* for commit-rec LR header - note: padding will subsume the ophdr */
3445         unit_bytes += log->l_iclog_hsize;
3446
3447         /* for roundoff padding for transaction data and one for commit record */
3448         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb) &&
3449             log->l_mp->m_sb.sb_logsunit > 1) {
3450                 /* log su roundoff */
3451                 unit_bytes += 2*log->l_mp->m_sb.sb_logsunit;
3452         } else {
3453                 /* BB roundoff */
3454                 unit_bytes += 2*BBSIZE;
3455         }
3456
3457         atomic_set(&tic->t_ref, 1);
3458         tic->t_unit_res         = unit_bytes;
3459         tic->t_curr_res         = unit_bytes;
3460         tic->t_cnt              = cnt;
3461         tic->t_ocnt             = cnt;
3462         tic->t_tid              = random32();
3463         tic->t_clientid         = client;
3464         tic->t_flags            = XLOG_TIC_INITED;
3465         tic->t_trans_type       = 0;
3466         if (xflags & XFS_LOG_PERM_RESERV)
3467                 tic->t_flags |= XLOG_TIC_PERM_RESERV;
3468         sv_init(&tic->t_wait, SV_DEFAULT, "logtick");
3469
3470         xlog_tic_reset_res(tic);
3471
3472         return tic;
3473 }
3474
3475
3476 /******************************************************************************
3477  *
3478  *              Log debug routines
3479  *
3480  ******************************************************************************
3481  */
3482 #if defined(DEBUG)
3483 /*
3484  * Make sure that the destination ptr is within the valid data region of
3485  * one of the iclogs.  This uses backup pointers stored in a different
3486  * part of the log in case we trash the log structure.
3487  */
3488 void
3489 xlog_verify_dest_ptr(
3490         struct log      *log,
3491         char            *ptr)
3492 {
3493         int i;
3494         int good_ptr = 0;
3495
3496         for (i = 0; i < log->l_iclog_bufs; i++) {
3497                 if (ptr >= log->l_iclog_bak[i] &&
3498                     ptr <= log->l_iclog_bak[i] + log->l_iclog_size)
3499                         good_ptr++;
3500         }
3501
3502         if (!good_ptr)
3503                 xlog_panic("xlog_verify_dest_ptr: invalid ptr");
3504 }
3505
3506 STATIC void
3507 xlog_verify_grant_head(xlog_t *log, int equals)
3508 {
3509     if (log->l_grant_reserve_cycle == log->l_grant_write_cycle) {
3510         if (equals)
3511             ASSERT(log->l_grant_reserve_bytes >= log->l_grant_write_bytes);
3512         else
3513             ASSERT(log->l_grant_reserve_bytes > log->l_grant_write_bytes);
3514     } else {
3515         ASSERT(log->l_grant_reserve_cycle-1 == log->l_grant_write_cycle);
3516         ASSERT(log->l_grant_write_bytes >= log->l_grant_reserve_bytes);
3517     }
3518 }       /* xlog_verify_grant_head */
3519
3520 /* check if it will fit */
3521 STATIC void
3522 xlog_verify_tail_lsn(xlog_t         *log,
3523                      xlog_in_core_t *iclog,
3524                      xfs_lsn_t      tail_lsn)
3525 {
3526     int blocks;
3527
3528     if (CYCLE_LSN(tail_lsn) == log->l_prev_cycle) {
3529         blocks =
3530             log->l_logBBsize - (log->l_prev_block - BLOCK_LSN(tail_lsn));
3531         if (blocks < BTOBB(iclog->ic_offset)+BTOBB(log->l_iclog_hsize))
3532             xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3533     } else {
3534         ASSERT(CYCLE_LSN(tail_lsn)+1 == log->l_prev_cycle);
3535
3536         if (BLOCK_LSN(tail_lsn) == log->l_prev_block)
3537             xlog_panic("xlog_verify_tail_lsn: tail wrapped");
3538
3539         blocks = BLOCK_LSN(tail_lsn) - log->l_prev_block;
3540         if (blocks < BTOBB(iclog->ic_offset) + 1)
3541             xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3542     }
3543 }       /* xlog_verify_tail_lsn */
3544
3545 /*
3546  * Perform a number of checks on the iclog before writing to disk.
3547  *
3548  * 1. Make sure the iclogs are still circular
3549  * 2. Make sure we have a good magic number
3550  * 3. Make sure we don't have magic numbers in the data
3551  * 4. Check fields of each log operation header for:
3552  *      A. Valid client identifier
3553  *      B. tid ptr value falls in valid ptr space (user space code)
3554  *      C. Length in log record header is correct according to the
3555  *              individual operation headers within record.
3556  * 5. When a bwrite will occur within 5 blocks of the front of the physical
3557  *      log, check the preceding blocks of the physical log to make sure all
3558  *      the cycle numbers agree with the current cycle number.
3559  */
3560 STATIC void
3561 xlog_verify_iclog(xlog_t         *log,
3562                   xlog_in_core_t *iclog,
3563                   int            count,
3564                   boolean_t      syncing)
3565 {
3566         xlog_op_header_t        *ophead;
3567         xlog_in_core_t          *icptr;
3568         xlog_in_core_2_t        *xhdr;
3569         xfs_caddr_t             ptr;
3570         xfs_caddr_t             base_ptr;
3571         __psint_t               field_offset;
3572         __uint8_t               clientid;
3573         int                     len, i, j, k, op_len;
3574         int                     idx;
3575
3576         /* check validity of iclog pointers */
3577         spin_lock(&log->l_icloglock);
3578         icptr = log->l_iclog;
3579         for (i=0; i < log->l_iclog_bufs; i++) {
3580                 if (icptr == NULL)
3581                         xlog_panic("xlog_verify_iclog: invalid ptr");
3582                 icptr = icptr->ic_next;
3583         }
3584         if (icptr != log->l_iclog)
3585                 xlog_panic("xlog_verify_iclog: corrupt iclog ring");
3586         spin_unlock(&log->l_icloglock);
3587
3588         /* check log magic numbers */
3589         if (be32_to_cpu(iclog->ic_header.h_magicno) != XLOG_HEADER_MAGIC_NUM)
3590                 xlog_panic("xlog_verify_iclog: invalid magic num");
3591
3592         ptr = (xfs_caddr_t) &iclog->ic_header;
3593         for (ptr += BBSIZE; ptr < ((xfs_caddr_t)&iclog->ic_header) + count;
3594              ptr += BBSIZE) {
3595                 if (be32_to_cpu(*(__be32 *)ptr) == XLOG_HEADER_MAGIC_NUM)
3596                         xlog_panic("xlog_verify_iclog: unexpected magic num");
3597         }
3598
3599         /* check fields */
3600         len = be32_to_cpu(iclog->ic_header.h_num_logops);
3601         ptr = iclog->ic_datap;
3602         base_ptr = ptr;
3603         ophead = (xlog_op_header_t *)ptr;
3604         xhdr = iclog->ic_data;
3605         for (i = 0; i < len; i++) {
3606                 ophead = (xlog_op_header_t *)ptr;
3607
3608                 /* clientid is only 1 byte */
3609                 field_offset = (__psint_t)
3610                                ((xfs_caddr_t)&(ophead->oh_clientid) - base_ptr);
3611                 if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3612                         clientid = ophead->oh_clientid;
3613                 } else {
3614                         idx = BTOBBT((xfs_caddr_t)&(ophead->oh_clientid) - iclog->ic_datap);
3615                         if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3616                                 j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3617                                 k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3618                                 clientid = xlog_get_client_id(
3619                                         xhdr[j].hic_xheader.xh_cycle_data[k]);
3620                         } else {
3621                                 clientid = xlog_get_client_id(
3622                                         iclog->ic_header.h_cycle_data[idx]);
3623                         }
3624                 }
3625                 if (clientid != XFS_TRANSACTION && clientid != XFS_LOG)
3626                         cmn_err(CE_WARN, "xlog_verify_iclog: "
3627                                 "invalid clientid %d op 0x%p offset 0x%lx",
3628                                 clientid, ophead, (unsigned long)field_offset);
3629
3630                 /* check length */
3631                 field_offset = (__psint_t)
3632                                ((xfs_caddr_t)&(ophead->oh_len) - base_ptr);
3633                 if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3634                         op_len = be32_to_cpu(ophead->oh_len);
3635                 } else {
3636                         idx = BTOBBT((__psint_t)&ophead->oh_len -
3637                                     (__psint_t)iclog->ic_datap);
3638                         if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3639                                 j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3640                                 k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3641                                 op_len = be32_to_cpu(xhdr[j].hic_xheader.xh_cycle_data[k]);
3642                         } else {
3643                                 op_len = be32_to_cpu(iclog->ic_header.h_cycle_data[idx]);
3644                         }
3645                 }
3646                 ptr += sizeof(xlog_op_header_t) + op_len;
3647         }
3648 }       /* xlog_verify_iclog */
3649 #endif
3650
3651 /*
3652  * Mark all iclogs IOERROR. l_icloglock is held by the caller.
3653  */
3654 STATIC int
3655 xlog_state_ioerror(
3656         xlog_t  *log)
3657 {
3658         xlog_in_core_t  *iclog, *ic;
3659
3660         iclog = log->l_iclog;
3661         if (! (iclog->ic_state & XLOG_STATE_IOERROR)) {
3662                 /*
3663                  * Mark all the incore logs IOERROR.
3664                  * From now on, no log flushes will result.
3665                  */
3666                 ic = iclog;
3667                 do {
3668                         ic->ic_state = XLOG_STATE_IOERROR;
3669                         ic = ic->ic_next;
3670                 } while (ic != iclog);
3671                 return 0;
3672         }
3673         /*
3674          * Return non-zero, if state transition has already happened.
3675          */
3676         return 1;
3677 }
3678
3679 /*
3680  * This is called from xfs_force_shutdown, when we're forcibly
3681  * shutting down the filesystem, typically because of an IO error.
3682  * Our main objectives here are to make sure that:
3683  *      a. the filesystem gets marked 'SHUTDOWN' for all interested
3684  *         parties to find out, 'atomically'.
3685  *      b. those who're sleeping on log reservations, pinned objects and
3686  *          other resources get woken up, and be told the bad news.
3687  *      c. nothing new gets queued up after (a) and (b) are done.
3688  *      d. if !logerror, flush the iclogs to disk, then seal them off
3689  *         for business.
3690  *
3691  * Note: for delayed logging the !logerror case needs to flush the regions
3692  * held in memory out to the iclogs before flushing them to disk. This needs
3693  * to be done before the log is marked as shutdown, otherwise the flush to the
3694  * iclogs will fail.
3695  */
3696 int
3697 xfs_log_force_umount(
3698         struct xfs_mount        *mp,
3699         int                     logerror)
3700 {
3701         xlog_ticket_t   *tic;
3702         xlog_t          *log;
3703         int             retval;
3704
3705         log = mp->m_log;
3706
3707         /*
3708          * If this happens during log recovery, don't worry about
3709          * locking; the log isn't open for business yet.
3710          */
3711         if (!log ||
3712             log->l_flags & XLOG_ACTIVE_RECOVERY) {
3713                 mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3714                 if (mp->m_sb_bp)
3715                         XFS_BUF_DONE(mp->m_sb_bp);
3716                 return 0;
3717         }
3718
3719         /*
3720          * Somebody could've already done the hard work for us.
3721          * No need to get locks for this.
3722          */
3723         if (logerror && log->l_iclog->ic_state & XLOG_STATE_IOERROR) {
3724                 ASSERT(XLOG_FORCED_SHUTDOWN(log));
3725                 return 1;
3726         }
3727         retval = 0;
3728
3729         /*
3730          * Flush the in memory commit item list before marking the log as
3731          * being shut down. We need to do it in this order to ensure all the
3732          * completed transactions are flushed to disk with the xfs_log_force()
3733          * call below.
3734          */
3735         if (!logerror && (mp->m_flags & XFS_MOUNT_DELAYLOG))
3736                 xlog_cil_push(log, 1);
3737
3738         /*
3739          * We must hold both the GRANT lock and the LOG lock,
3740          * before we mark the filesystem SHUTDOWN and wake
3741          * everybody up to tell the bad news.
3742          */
3743         spin_lock(&log->l_icloglock);
3744         spin_lock(&log->l_grant_lock);
3745         mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3746         if (mp->m_sb_bp)
3747                 XFS_BUF_DONE(mp->m_sb_bp);
3748
3749         /*
3750          * This flag is sort of redundant because of the mount flag, but
3751          * it's good to maintain the separation between the log and the rest
3752          * of XFS.
3753          */
3754         log->l_flags |= XLOG_IO_ERROR;
3755
3756         /*
3757          * If we hit a log error, we want to mark all the iclogs IOERROR
3758          * while we're still holding the loglock.
3759          */
3760         if (logerror)
3761                 retval = xlog_state_ioerror(log);
3762         spin_unlock(&log->l_icloglock);
3763
3764         /*
3765          * We don't want anybody waiting for log reservations
3766          * after this. That means we have to wake up everybody
3767          * queued up on reserve_headq as well as write_headq.
3768          * In addition, we make sure in xlog_{re}grant_log_space
3769          * that we don't enqueue anything once the SHUTDOWN flag
3770          * is set, and this action is protected by the GRANTLOCK.
3771          */
3772         if ((tic = log->l_reserve_headq)) {
3773                 do {
3774                         sv_signal(&tic->t_wait);
3775                         tic = tic->t_next;
3776                 } while (tic != log->l_reserve_headq);
3777         }
3778
3779         if ((tic = log->l_write_headq)) {
3780                 do {
3781                         sv_signal(&tic->t_wait);
3782                         tic = tic->t_next;
3783                 } while (tic != log->l_write_headq);
3784         }
3785         spin_unlock(&log->l_grant_lock);
3786
3787         if (!(log->l_iclog->ic_state & XLOG_STATE_IOERROR)) {
3788                 ASSERT(!logerror);
3789                 /*
3790                  * Force the incore logs to disk before shutting the
3791                  * log down completely.
3792                  */
3793                 _xfs_log_force(mp, XFS_LOG_SYNC, NULL);
3794
3795                 spin_lock(&log->l_icloglock);
3796                 retval = xlog_state_ioerror(log);
3797                 spin_unlock(&log->l_icloglock);
3798         }
3799         /*
3800          * Wake up everybody waiting on xfs_log_force.
3801          * Callback all log item committed functions as if the
3802          * log writes were completed.
3803          */
3804         xlog_state_do_callback(log, XFS_LI_ABORTED, NULL);
3805
3806 #ifdef XFSERRORDEBUG
3807         {
3808                 xlog_in_core_t  *iclog;
3809
3810                 spin_lock(&log->l_icloglock);
3811                 iclog = log->l_iclog;
3812                 do {
3813                         ASSERT(iclog->ic_callback == 0);
3814                         iclog = iclog->ic_next;
3815                 } while (iclog != log->l_iclog);
3816                 spin_unlock(&log->l_icloglock);
3817         }
3818 #endif
3819         /* return non-zero if log IOERROR transition had already happened */
3820         return retval;
3821 }
3822
3823 STATIC int
3824 xlog_iclogs_empty(xlog_t *log)
3825 {
3826         xlog_in_core_t  *iclog;
3827
3828         iclog = log->l_iclog;
3829         do {
3830                 /* endianness does not matter here, zero is zero in
3831                  * any language.
3832                  */
3833                 if (iclog->ic_header.h_num_logops)
3834                         return 0;
3835                 iclog = iclog->ic_next;
3836         } while (iclog != log->l_iclog);
3837         return 1;
3838 }