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