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