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