Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/roland...
[linux-2.6] / 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 _XFS_BARRIER_FAILED flag was set by a lower
1037          * layer, it means the underlying device no longer supports
1038          * barrier I/O. Warn loudly and turn off barriers.
1039          */
1040         if (bp->b_flags & _XFS_BARRIER_FAILED) {
1041                 bp->b_flags &= ~_XFS_BARRIER_FAILED;
1042                 l->l_mp->m_flags &= ~XFS_MOUNT_BARRIER;
1043                 xfs_fs_cmn_err(CE_WARN, l->l_mp,
1044                                 "xlog_iodone: Barriers are no longer supported"
1045                                 " by device. Disabling barriers\n");
1046                 xfs_buftrace("XLOG_IODONE BARRIERS OFF", bp);
1047         }
1048
1049         /*
1050          * Race to shutdown the filesystem if we see an error.
1051          */
1052         if (XFS_TEST_ERROR((XFS_BUF_GETERROR(bp)), l->l_mp,
1053                         XFS_ERRTAG_IODONE_IOERR, XFS_RANDOM_IODONE_IOERR)) {
1054                 xfs_ioerror_alert("xlog_iodone", l->l_mp, bp, XFS_BUF_ADDR(bp));
1055                 XFS_BUF_STALE(bp);
1056                 xfs_force_shutdown(l->l_mp, SHUTDOWN_LOG_IO_ERROR);
1057                 /*
1058                  * This flag will be propagated to the trans-committed
1059                  * callback routines to let them know that the log-commit
1060                  * didn't succeed.
1061                  */
1062                 aborted = XFS_LI_ABORTED;
1063         } else if (iclog->ic_state & XLOG_STATE_IOERROR) {
1064                 aborted = XFS_LI_ABORTED;
1065         }
1066
1067         /* log I/O is always issued ASYNC */
1068         ASSERT(XFS_BUF_ISASYNC(bp));
1069         xlog_state_done_syncing(iclog, aborted);
1070         /*
1071          * do not reference the buffer (bp) here as we could race
1072          * with it being freed after writing the unmount record to the
1073          * log.
1074          */
1075
1076 }       /* xlog_iodone */
1077
1078 /*
1079  * The bdstrat callback function for log bufs. This gives us a central
1080  * place to trap bufs in case we get hit by a log I/O error and need to
1081  * shutdown. Actually, in practice, even when we didn't get a log error,
1082  * we transition the iclogs to IOERROR state *after* flushing all existing
1083  * iclogs to disk. This is because we don't want anymore new transactions to be
1084  * started or completed afterwards.
1085  */
1086 STATIC int
1087 xlog_bdstrat_cb(struct xfs_buf *bp)
1088 {
1089         xlog_in_core_t *iclog;
1090
1091         iclog = XFS_BUF_FSPRIVATE(bp, xlog_in_core_t *);
1092
1093         if ((iclog->ic_state & XLOG_STATE_IOERROR) == 0) {
1094           /* note for irix bstrat will need  struct bdevsw passed
1095            * Fix the following macro if the code ever is merged
1096            */
1097             XFS_bdstrat(bp);
1098                 return 0;
1099         }
1100
1101         xfs_buftrace("XLOG__BDSTRAT IOERROR", bp);
1102         XFS_BUF_ERROR(bp, EIO);
1103         XFS_BUF_STALE(bp);
1104         xfs_biodone(bp);
1105         return XFS_ERROR(EIO);
1106
1107
1108 }
1109
1110 /*
1111  * Return size of each in-core log record buffer.
1112  *
1113  * All machines get 8 x 32KB buffers by default, unless tuned otherwise.
1114  *
1115  * If the filesystem blocksize is too large, we may need to choose a
1116  * larger size since the directory code currently logs entire blocks.
1117  */
1118
1119 STATIC void
1120 xlog_get_iclog_buffer_size(xfs_mount_t  *mp,
1121                            xlog_t       *log)
1122 {
1123         int size;
1124         int xhdrs;
1125
1126         if (mp->m_logbufs <= 0)
1127                 log->l_iclog_bufs = XLOG_MAX_ICLOGS;
1128         else
1129                 log->l_iclog_bufs = mp->m_logbufs;
1130
1131         /*
1132          * Buffer size passed in from mount system call.
1133          */
1134         if (mp->m_logbsize > 0) {
1135                 size = log->l_iclog_size = mp->m_logbsize;
1136                 log->l_iclog_size_log = 0;
1137                 while (size != 1) {
1138                         log->l_iclog_size_log++;
1139                         size >>= 1;
1140                 }
1141
1142                 if (xfs_sb_version_haslogv2(&mp->m_sb)) {
1143                         /* # headers = size / 32K
1144                          * one header holds cycles from 32K of data
1145                          */
1146
1147                         xhdrs = mp->m_logbsize / XLOG_HEADER_CYCLE_SIZE;
1148                         if (mp->m_logbsize % XLOG_HEADER_CYCLE_SIZE)
1149                                 xhdrs++;
1150                         log->l_iclog_hsize = xhdrs << BBSHIFT;
1151                         log->l_iclog_heads = xhdrs;
1152                 } else {
1153                         ASSERT(mp->m_logbsize <= XLOG_BIG_RECORD_BSIZE);
1154                         log->l_iclog_hsize = BBSIZE;
1155                         log->l_iclog_heads = 1;
1156                 }
1157                 goto done;
1158         }
1159
1160         /* All machines use 32KB buffers by default. */
1161         log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;
1162         log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
1163
1164         /* the default log size is 16k or 32k which is one header sector */
1165         log->l_iclog_hsize = BBSIZE;
1166         log->l_iclog_heads = 1;
1167
1168         /*
1169          * For 16KB, we use 3 32KB buffers.  For 32KB block sizes, we use
1170          * 4 32KB buffers.  For 64KB block sizes, we use 8 32KB buffers.
1171          */
1172         if (mp->m_sb.sb_blocksize >= 16*1024) {
1173                 log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;
1174                 log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
1175                 if (mp->m_logbufs <= 0) {
1176                         switch (mp->m_sb.sb_blocksize) {
1177                             case 16*1024:                       /* 16 KB */
1178                                 log->l_iclog_bufs = 3;
1179                                 break;
1180                             case 32*1024:                       /* 32 KB */
1181                                 log->l_iclog_bufs = 4;
1182                                 break;
1183                             case 64*1024:                       /* 64 KB */
1184                                 log->l_iclog_bufs = 8;
1185                                 break;
1186                             default:
1187                                 xlog_panic("XFS: Invalid blocksize");
1188                                 break;
1189                         }
1190                 }
1191         }
1192
1193 done:   /* are we being asked to make the sizes selected above visible? */
1194         if (mp->m_logbufs == 0)
1195                 mp->m_logbufs = log->l_iclog_bufs;
1196         if (mp->m_logbsize == 0)
1197                 mp->m_logbsize = log->l_iclog_size;
1198 }       /* xlog_get_iclog_buffer_size */
1199
1200
1201 /*
1202  * This routine initializes some of the log structure for a given mount point.
1203  * Its primary purpose is to fill in enough, so recovery can occur.  However,
1204  * some other stuff may be filled in too.
1205  */
1206 STATIC xlog_t *
1207 xlog_alloc_log(xfs_mount_t      *mp,
1208                xfs_buftarg_t    *log_target,
1209                xfs_daddr_t      blk_offset,
1210                int              num_bblks)
1211 {
1212         xlog_t                  *log;
1213         xlog_rec_header_t       *head;
1214         xlog_in_core_t          **iclogp;
1215         xlog_in_core_t          *iclog, *prev_iclog=NULL;
1216         xfs_buf_t               *bp;
1217         int                     i;
1218         int                     iclogsize;
1219
1220         log = (xlog_t *)kmem_zalloc(sizeof(xlog_t), KM_SLEEP);
1221
1222         log->l_mp          = mp;
1223         log->l_targ        = log_target;
1224         log->l_logsize     = BBTOB(num_bblks);
1225         log->l_logBBstart  = blk_offset;
1226         log->l_logBBsize   = num_bblks;
1227         log->l_covered_state = XLOG_STATE_COVER_IDLE;
1228         log->l_flags       |= XLOG_ACTIVE_RECOVERY;
1229
1230         log->l_prev_block  = -1;
1231         log->l_tail_lsn    = xlog_assign_lsn(1, 0);
1232         /* log->l_tail_lsn = 0x100000000LL; cycle = 1; current block = 0 */
1233         log->l_last_sync_lsn = log->l_tail_lsn;
1234         log->l_curr_cycle  = 1;     /* 0 is bad since this is initial value */
1235         log->l_grant_reserve_cycle = 1;
1236         log->l_grant_write_cycle = 1;
1237
1238         if (xfs_sb_version_hassector(&mp->m_sb)) {
1239                 log->l_sectbb_log = mp->m_sb.sb_logsectlog - BBSHIFT;
1240                 ASSERT(log->l_sectbb_log <= mp->m_sectbb_log);
1241                 /* for larger sector sizes, must have v2 or external log */
1242                 ASSERT(log->l_sectbb_log == 0 ||
1243                         log->l_logBBstart == 0 ||
1244                         xfs_sb_version_haslogv2(&mp->m_sb));
1245                 ASSERT(mp->m_sb.sb_logsectlog >= BBSHIFT);
1246         }
1247         log->l_sectbb_mask = (1 << log->l_sectbb_log) - 1;
1248
1249         xlog_get_iclog_buffer_size(mp, log);
1250
1251         bp = xfs_buf_get_empty(log->l_iclog_size, mp->m_logdev_targp);
1252         XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1253         XFS_BUF_SET_BDSTRAT_FUNC(bp, xlog_bdstrat_cb);
1254         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
1255         ASSERT(XFS_BUF_ISBUSY(bp));
1256         ASSERT(XFS_BUF_VALUSEMA(bp) <= 0);
1257         log->l_xbuf = bp;
1258
1259         spin_lock_init(&log->l_icloglock);
1260         spin_lock_init(&log->l_grant_lock);
1261         sv_init(&log->l_flush_wait, 0, "flush_wait");
1262
1263         xlog_trace_loggrant_alloc(log);
1264         /* log record size must be multiple of BBSIZE; see xlog_rec_header_t */
1265         ASSERT((XFS_BUF_SIZE(bp) & BBMASK) == 0);
1266
1267         iclogp = &log->l_iclog;
1268         /*
1269          * The amount of memory to allocate for the iclog structure is
1270          * rather funky due to the way the structure is defined.  It is
1271          * done this way so that we can use different sizes for machines
1272          * with different amounts of memory.  See the definition of
1273          * xlog_in_core_t in xfs_log_priv.h for details.
1274          */
1275         iclogsize = log->l_iclog_size;
1276         ASSERT(log->l_iclog_size >= 4096);
1277         for (i=0; i < log->l_iclog_bufs; i++) {
1278                 *iclogp = (xlog_in_core_t *)
1279                           kmem_zalloc(sizeof(xlog_in_core_t), KM_SLEEP);
1280                 iclog = *iclogp;
1281                 iclog->ic_prev = prev_iclog;
1282                 prev_iclog = iclog;
1283
1284                 bp = xfs_buf_get_noaddr(log->l_iclog_size, mp->m_logdev_targp);
1285                 if (!XFS_BUF_CPSEMA(bp))
1286                         ASSERT(0);
1287                 XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1288                 XFS_BUF_SET_BDSTRAT_FUNC(bp, xlog_bdstrat_cb);
1289                 XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
1290                 iclog->ic_bp = bp;
1291                 iclog->hic_data = bp->b_addr;
1292 #ifdef DEBUG
1293                 log->l_iclog_bak[i] = (xfs_caddr_t)&(iclog->ic_header);
1294 #endif
1295                 head = &iclog->ic_header;
1296                 memset(head, 0, sizeof(xlog_rec_header_t));
1297                 head->h_magicno = cpu_to_be32(XLOG_HEADER_MAGIC_NUM);
1298                 head->h_version = cpu_to_be32(
1299                         xfs_sb_version_haslogv2(&log->l_mp->m_sb) ? 2 : 1);
1300                 head->h_size = cpu_to_be32(log->l_iclog_size);
1301                 /* new fields */
1302                 head->h_fmt = cpu_to_be32(XLOG_FMT);
1303                 memcpy(&head->h_fs_uuid, &mp->m_sb.sb_uuid, sizeof(uuid_t));
1304
1305                 iclog->ic_size = XFS_BUF_SIZE(bp) - log->l_iclog_hsize;
1306                 iclog->ic_state = XLOG_STATE_ACTIVE;
1307                 iclog->ic_log = log;
1308                 atomic_set(&iclog->ic_refcnt, 0);
1309                 spin_lock_init(&iclog->ic_callback_lock);
1310                 iclog->ic_callback_tail = &(iclog->ic_callback);
1311                 iclog->ic_datap = (char *)iclog->hic_data + log->l_iclog_hsize;
1312
1313                 ASSERT(XFS_BUF_ISBUSY(iclog->ic_bp));
1314                 ASSERT(XFS_BUF_VALUSEMA(iclog->ic_bp) <= 0);
1315                 sv_init(&iclog->ic_force_wait, SV_DEFAULT, "iclog-force");
1316                 sv_init(&iclog->ic_write_wait, SV_DEFAULT, "iclog-write");
1317
1318                 xlog_trace_iclog_alloc(iclog);
1319
1320                 iclogp = &iclog->ic_next;
1321         }
1322         *iclogp = log->l_iclog;                 /* complete ring */
1323         log->l_iclog->ic_prev = prev_iclog;     /* re-write 1st prev ptr */
1324
1325         return log;
1326 }       /* xlog_alloc_log */
1327
1328
1329 /*
1330  * Write out the commit record of a transaction associated with the given
1331  * ticket.  Return the lsn of the commit record.
1332  */
1333 STATIC int
1334 xlog_commit_record(xfs_mount_t  *mp,
1335                    xlog_ticket_t *ticket,
1336                    xlog_in_core_t **iclog,
1337                    xfs_lsn_t    *commitlsnp)
1338 {
1339         int             error;
1340         xfs_log_iovec_t reg[1];
1341
1342         reg[0].i_addr = NULL;
1343         reg[0].i_len = 0;
1344         XLOG_VEC_SET_TYPE(&reg[0], XLOG_REG_TYPE_COMMIT);
1345
1346         ASSERT_ALWAYS(iclog);
1347         if ((error = xlog_write(mp, reg, 1, ticket, commitlsnp,
1348                                iclog, XLOG_COMMIT_TRANS))) {
1349                 xfs_force_shutdown(mp, SHUTDOWN_LOG_IO_ERROR);
1350         }
1351         return error;
1352 }       /* xlog_commit_record */
1353
1354
1355 /*
1356  * Push on the buffer cache code if we ever use more than 75% of the on-disk
1357  * log space.  This code pushes on the lsn which would supposedly free up
1358  * the 25% which we want to leave free.  We may need to adopt a policy which
1359  * pushes on an lsn which is further along in the log once we reach the high
1360  * water mark.  In this manner, we would be creating a low water mark.
1361  */
1362 STATIC void
1363 xlog_grant_push_ail(xfs_mount_t *mp,
1364                     int         need_bytes)
1365 {
1366     xlog_t      *log = mp->m_log;       /* pointer to the log */
1367     xfs_lsn_t   tail_lsn;               /* lsn of the log tail */
1368     xfs_lsn_t   threshold_lsn = 0;      /* lsn we'd like to be at */
1369     int         free_blocks;            /* free blocks left to write to */
1370     int         free_bytes;             /* free bytes left to write to */
1371     int         threshold_block;        /* block in lsn we'd like to be at */
1372     int         threshold_cycle;        /* lsn cycle we'd like to be at */
1373     int         free_threshold;
1374
1375     ASSERT(BTOBB(need_bytes) < log->l_logBBsize);
1376
1377     spin_lock(&log->l_grant_lock);
1378     free_bytes = xlog_space_left(log,
1379                                  log->l_grant_reserve_cycle,
1380                                  log->l_grant_reserve_bytes);
1381     tail_lsn = log->l_tail_lsn;
1382     free_blocks = BTOBBT(free_bytes);
1383
1384     /*
1385      * Set the threshold for the minimum number of free blocks in the
1386      * log to the maximum of what the caller needs, one quarter of the
1387      * log, and 256 blocks.
1388      */
1389     free_threshold = BTOBB(need_bytes);
1390     free_threshold = MAX(free_threshold, (log->l_logBBsize >> 2));
1391     free_threshold = MAX(free_threshold, 256);
1392     if (free_blocks < free_threshold) {
1393         threshold_block = BLOCK_LSN(tail_lsn) + free_threshold;
1394         threshold_cycle = CYCLE_LSN(tail_lsn);
1395         if (threshold_block >= log->l_logBBsize) {
1396             threshold_block -= log->l_logBBsize;
1397             threshold_cycle += 1;
1398         }
1399         threshold_lsn = xlog_assign_lsn(threshold_cycle, threshold_block);
1400
1401         /* Don't pass in an lsn greater than the lsn of the last
1402          * log record known to be on disk.
1403          */
1404         if (XFS_LSN_CMP(threshold_lsn, log->l_last_sync_lsn) > 0)
1405             threshold_lsn = log->l_last_sync_lsn;
1406     }
1407     spin_unlock(&log->l_grant_lock);
1408
1409     /*
1410      * Get the transaction layer to kick the dirty buffers out to
1411      * disk asynchronously. No point in trying to do this if
1412      * the filesystem is shutting down.
1413      */
1414     if (threshold_lsn &&
1415         !XLOG_FORCED_SHUTDOWN(log))
1416             xfs_trans_push_ail(mp, threshold_lsn);
1417 }       /* xlog_grant_push_ail */
1418
1419
1420 /*
1421  * Flush out the in-core log (iclog) to the on-disk log in an asynchronous 
1422  * fashion.  Previously, we should have moved the current iclog
1423  * ptr in the log to point to the next available iclog.  This allows further
1424  * write to continue while this code syncs out an iclog ready to go.
1425  * Before an in-core log can be written out, the data section must be scanned
1426  * to save away the 1st word of each BBSIZE block into the header.  We replace
1427  * it with the current cycle count.  Each BBSIZE block is tagged with the
1428  * cycle count because there in an implicit assumption that drives will
1429  * guarantee that entire 512 byte blocks get written at once.  In other words,
1430  * we can't have part of a 512 byte block written and part not written.  By
1431  * tagging each block, we will know which blocks are valid when recovering
1432  * after an unclean shutdown.
1433  *
1434  * This routine is single threaded on the iclog.  No other thread can be in
1435  * this routine with the same iclog.  Changing contents of iclog can there-
1436  * fore be done without grabbing the state machine lock.  Updating the global
1437  * log will require grabbing the lock though.
1438  *
1439  * The entire log manager uses a logical block numbering scheme.  Only
1440  * log_sync (and then only bwrite()) know about the fact that the log may
1441  * not start with block zero on a given device.  The log block start offset
1442  * is added immediately before calling bwrite().
1443  */
1444
1445 STATIC int
1446 xlog_sync(xlog_t                *log,
1447           xlog_in_core_t        *iclog)
1448 {
1449         xfs_caddr_t     dptr;           /* pointer to byte sized element */
1450         xfs_buf_t       *bp;
1451         int             i;
1452         uint            count;          /* byte count of bwrite */
1453         uint            count_init;     /* initial count before roundup */
1454         int             roundoff;       /* roundoff to BB or stripe */
1455         int             split = 0;      /* split write into two regions */
1456         int             error;
1457         int             v2 = xfs_sb_version_haslogv2(&log->l_mp->m_sb);
1458
1459         XFS_STATS_INC(xs_log_writes);
1460         ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
1461
1462         /* Add for LR header */
1463         count_init = log->l_iclog_hsize + iclog->ic_offset;
1464
1465         /* Round out the log write size */
1466         if (v2 && log->l_mp->m_sb.sb_logsunit > 1) {
1467                 /* we have a v2 stripe unit to use */
1468                 count = XLOG_LSUNITTOB(log, XLOG_BTOLSUNIT(log, count_init));
1469         } else {
1470                 count = BBTOB(BTOBB(count_init));
1471         }
1472         roundoff = count - count_init;
1473         ASSERT(roundoff >= 0);
1474         ASSERT((v2 && log->l_mp->m_sb.sb_logsunit > 1 && 
1475                 roundoff < log->l_mp->m_sb.sb_logsunit)
1476                 || 
1477                 (log->l_mp->m_sb.sb_logsunit <= 1 && 
1478                  roundoff < BBTOB(1)));
1479
1480         /* move grant heads by roundoff in sync */
1481         spin_lock(&log->l_grant_lock);
1482         xlog_grant_add_space(log, roundoff);
1483         spin_unlock(&log->l_grant_lock);
1484
1485         /* put cycle number in every block */
1486         xlog_pack_data(log, iclog, roundoff); 
1487
1488         /* real byte length */
1489         if (v2) {
1490                 iclog->ic_header.h_len =
1491                         cpu_to_be32(iclog->ic_offset + roundoff);
1492         } else {
1493                 iclog->ic_header.h_len =
1494                         cpu_to_be32(iclog->ic_offset);
1495         }
1496
1497         bp = iclog->ic_bp;
1498         ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) == (unsigned long)1);
1499         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1500         XFS_BUF_SET_ADDR(bp, BLOCK_LSN(be64_to_cpu(iclog->ic_header.h_lsn)));
1501
1502         XFS_STATS_ADD(xs_log_blocks, BTOBB(count));
1503
1504         /* Do we need to split this write into 2 parts? */
1505         if (XFS_BUF_ADDR(bp) + BTOBB(count) > log->l_logBBsize) {
1506                 split = count - (BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp)));
1507                 count = BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp));
1508                 iclog->ic_bwritecnt = 2;        /* split into 2 writes */
1509         } else {
1510                 iclog->ic_bwritecnt = 1;
1511         }
1512         XFS_BUF_SET_COUNT(bp, count);
1513         XFS_BUF_SET_FSPRIVATE(bp, iclog);       /* save for later */
1514         XFS_BUF_ZEROFLAGS(bp);
1515         XFS_BUF_BUSY(bp);
1516         XFS_BUF_ASYNC(bp);
1517         /*
1518          * Do an ordered write for the log block.
1519          * Its unnecessary to flush the first split block in the log wrap case.
1520          */
1521         if (!split && (log->l_mp->m_flags & XFS_MOUNT_BARRIER))
1522                 XFS_BUF_ORDERED(bp);
1523
1524         ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1525         ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1526
1527         xlog_verify_iclog(log, iclog, count, B_TRUE);
1528
1529         /* account for log which doesn't start at block #0 */
1530         XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1531         /*
1532          * Don't call xfs_bwrite here. We do log-syncs even when the filesystem
1533          * is shutting down.
1534          */
1535         XFS_BUF_WRITE(bp);
1536
1537         if ((error = XFS_bwrite(bp))) {
1538                 xfs_ioerror_alert("xlog_sync", log->l_mp, bp,
1539                                   XFS_BUF_ADDR(bp));
1540                 return error;
1541         }
1542         if (split) {
1543                 bp = iclog->ic_log->l_xbuf;
1544                 ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) ==
1545                                                         (unsigned long)1);
1546                 XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1547                 XFS_BUF_SET_ADDR(bp, 0);             /* logical 0 */
1548                 XFS_BUF_SET_PTR(bp, (xfs_caddr_t)((__psint_t)&(iclog->ic_header)+
1549                                             (__psint_t)count), split);
1550                 XFS_BUF_SET_FSPRIVATE(bp, iclog);
1551                 XFS_BUF_ZEROFLAGS(bp);
1552                 XFS_BUF_BUSY(bp);
1553                 XFS_BUF_ASYNC(bp);
1554                 if (log->l_mp->m_flags & XFS_MOUNT_BARRIER)
1555                         XFS_BUF_ORDERED(bp);
1556                 dptr = XFS_BUF_PTR(bp);
1557                 /*
1558                  * Bump the cycle numbers at the start of each block
1559                  * since this part of the buffer is at the start of
1560                  * a new cycle.  Watch out for the header magic number
1561                  * case, though.
1562                  */
1563                 for (i = 0; i < split; i += BBSIZE) {
1564                         be32_add_cpu((__be32 *)dptr, 1);
1565                         if (be32_to_cpu(*(__be32 *)dptr) == XLOG_HEADER_MAGIC_NUM)
1566                                 be32_add_cpu((__be32 *)dptr, 1);
1567                         dptr += BBSIZE;
1568                 }
1569
1570                 ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1571                 ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1572
1573                 /* account for internal log which doesn't start at block #0 */
1574                 XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1575                 XFS_BUF_WRITE(bp);
1576                 if ((error = XFS_bwrite(bp))) {
1577                         xfs_ioerror_alert("xlog_sync (split)", log->l_mp,
1578                                           bp, XFS_BUF_ADDR(bp));
1579                         return error;
1580                 }
1581         }
1582         return 0;
1583 }       /* xlog_sync */
1584
1585
1586 /*
1587  * Deallocate a log structure
1588  */
1589 STATIC void
1590 xlog_dealloc_log(xlog_t *log)
1591 {
1592         xlog_in_core_t  *iclog, *next_iclog;
1593         int             i;
1594
1595         iclog = log->l_iclog;
1596         for (i=0; i<log->l_iclog_bufs; i++) {
1597                 sv_destroy(&iclog->ic_force_wait);
1598                 sv_destroy(&iclog->ic_write_wait);
1599                 xfs_buf_free(iclog->ic_bp);
1600                 xlog_trace_iclog_dealloc(iclog);
1601                 next_iclog = iclog->ic_next;
1602                 kmem_free(iclog);
1603                 iclog = next_iclog;
1604         }
1605         spinlock_destroy(&log->l_icloglock);
1606         spinlock_destroy(&log->l_grant_lock);
1607
1608         xfs_buf_free(log->l_xbuf);
1609         xlog_trace_loggrant_dealloc(log);
1610         log->l_mp->m_log = NULL;
1611         kmem_free(log);
1612 }       /* xlog_dealloc_log */
1613
1614 /*
1615  * Update counters atomically now that memcpy is done.
1616  */
1617 /* ARGSUSED */
1618 static inline void
1619 xlog_state_finish_copy(xlog_t           *log,
1620                        xlog_in_core_t   *iclog,
1621                        int              record_cnt,
1622                        int              copy_bytes)
1623 {
1624         spin_lock(&log->l_icloglock);
1625
1626         be32_add_cpu(&iclog->ic_header.h_num_logops, record_cnt);
1627         iclog->ic_offset += copy_bytes;
1628
1629         spin_unlock(&log->l_icloglock);
1630 }       /* xlog_state_finish_copy */
1631
1632
1633
1634
1635 /*
1636  * print out info relating to regions written which consume
1637  * the reservation
1638  */
1639 STATIC void
1640 xlog_print_tic_res(xfs_mount_t *mp, xlog_ticket_t *ticket)
1641 {
1642         uint i;
1643         uint ophdr_spc = ticket->t_res_num_ophdrs * (uint)sizeof(xlog_op_header_t);
1644
1645         /* match with XLOG_REG_TYPE_* in xfs_log.h */
1646         static char *res_type_str[XLOG_REG_TYPE_MAX] = {
1647             "bformat",
1648             "bchunk",
1649             "efi_format",
1650             "efd_format",
1651             "iformat",
1652             "icore",
1653             "iext",
1654             "ibroot",
1655             "ilocal",
1656             "iattr_ext",
1657             "iattr_broot",
1658             "iattr_local",
1659             "qformat",
1660             "dquot",
1661             "quotaoff",
1662             "LR header",
1663             "unmount",
1664             "commit",
1665             "trans header"
1666         };
1667         static char *trans_type_str[XFS_TRANS_TYPE_MAX] = {
1668             "SETATTR_NOT_SIZE",
1669             "SETATTR_SIZE",
1670             "INACTIVE",
1671             "CREATE",
1672             "CREATE_TRUNC",
1673             "TRUNCATE_FILE",
1674             "REMOVE",
1675             "LINK",
1676             "RENAME",
1677             "MKDIR",
1678             "RMDIR",
1679             "SYMLINK",
1680             "SET_DMATTRS",
1681             "GROWFS",
1682             "STRAT_WRITE",
1683             "DIOSTRAT",
1684             "WRITE_SYNC",
1685             "WRITEID",
1686             "ADDAFORK",
1687             "ATTRINVAL",
1688             "ATRUNCATE",
1689             "ATTR_SET",
1690             "ATTR_RM",
1691             "ATTR_FLAG",
1692             "CLEAR_AGI_BUCKET",
1693             "QM_SBCHANGE",
1694             "DUMMY1",
1695             "DUMMY2",
1696             "QM_QUOTAOFF",
1697             "QM_DQALLOC",
1698             "QM_SETQLIM",
1699             "QM_DQCLUSTER",
1700             "QM_QINOCREATE",
1701             "QM_QUOTAOFF_END",
1702             "SB_UNIT",
1703             "FSYNC_TS",
1704             "GROWFSRT_ALLOC",
1705             "GROWFSRT_ZERO",
1706             "GROWFSRT_FREE",
1707             "SWAPEXT"
1708         };
1709
1710         xfs_fs_cmn_err(CE_WARN, mp,
1711                         "xfs_log_write: reservation summary:\n"
1712                         "  trans type  = %s (%u)\n"
1713                         "  unit res    = %d bytes\n"
1714                         "  current res = %d bytes\n"
1715                         "  total reg   = %u bytes (o/flow = %u bytes)\n"
1716                         "  ophdrs      = %u (ophdr space = %u bytes)\n"
1717                         "  ophdr + reg = %u bytes\n"
1718                         "  num regions = %u\n",
1719                         ((ticket->t_trans_type <= 0 ||
1720                           ticket->t_trans_type > XFS_TRANS_TYPE_MAX) ?
1721                           "bad-trans-type" : trans_type_str[ticket->t_trans_type-1]),
1722                         ticket->t_trans_type,
1723                         ticket->t_unit_res,
1724                         ticket->t_curr_res,
1725                         ticket->t_res_arr_sum, ticket->t_res_o_flow,
1726                         ticket->t_res_num_ophdrs, ophdr_spc,
1727                         ticket->t_res_arr_sum + 
1728                         ticket->t_res_o_flow + ophdr_spc,
1729                         ticket->t_res_num);
1730
1731         for (i = 0; i < ticket->t_res_num; i++) {
1732                 uint r_type = ticket->t_res_arr[i].r_type; 
1733                 cmn_err(CE_WARN,
1734                             "region[%u]: %s - %u bytes\n",
1735                             i, 
1736                             ((r_type <= 0 || r_type > XLOG_REG_TYPE_MAX) ?
1737                             "bad-rtype" : res_type_str[r_type-1]),
1738                             ticket->t_res_arr[i].r_len);
1739         }
1740 }
1741
1742 /*
1743  * Write some region out to in-core log
1744  *
1745  * This will be called when writing externally provided regions or when
1746  * writing out a commit record for a given transaction.
1747  *
1748  * General algorithm:
1749  *      1. Find total length of this write.  This may include adding to the
1750  *              lengths passed in.
1751  *      2. Check whether we violate the tickets reservation.
1752  *      3. While writing to this iclog
1753  *          A. Reserve as much space in this iclog as can get
1754  *          B. If this is first write, save away start lsn
1755  *          C. While writing this region:
1756  *              1. If first write of transaction, write start record
1757  *              2. Write log operation header (header per region)
1758  *              3. Find out if we can fit entire region into this iclog
1759  *              4. Potentially, verify destination memcpy ptr
1760  *              5. Memcpy (partial) region
1761  *              6. If partial copy, release iclog; otherwise, continue
1762  *                      copying more regions into current iclog
1763  *      4. Mark want sync bit (in simulation mode)
1764  *      5. Release iclog for potential flush to on-disk log.
1765  *
1766  * ERRORS:
1767  * 1.   Panic if reservation is overrun.  This should never happen since
1768  *      reservation amounts are generated internal to the filesystem.
1769  * NOTES:
1770  * 1. Tickets are single threaded data structures.
1771  * 2. The XLOG_END_TRANS & XLOG_CONTINUE_TRANS flags are passed down to the
1772  *      syncing routine.  When a single log_write region needs to span
1773  *      multiple in-core logs, the XLOG_CONTINUE_TRANS bit should be set
1774  *      on all log operation writes which don't contain the end of the
1775  *      region.  The XLOG_END_TRANS bit is used for the in-core log
1776  *      operation which contains the end of the continued log_write region.
1777  * 3. When xlog_state_get_iclog_space() grabs the rest of the current iclog,
1778  *      we don't really know exactly how much space will be used.  As a result,
1779  *      we don't update ic_offset until the end when we know exactly how many
1780  *      bytes have been written out.
1781  */
1782 STATIC int
1783 xlog_write(xfs_mount_t *        mp,
1784            xfs_log_iovec_t      reg[],
1785            int                  nentries,
1786            xfs_log_ticket_t     tic,
1787            xfs_lsn_t            *start_lsn,
1788            xlog_in_core_t       **commit_iclog,
1789            uint                 flags)
1790 {
1791     xlog_t           *log = mp->m_log;
1792     xlog_ticket_t    *ticket = (xlog_ticket_t *)tic;
1793     xlog_in_core_t   *iclog = NULL;  /* ptr to current in-core log */
1794     xlog_op_header_t *logop_head;    /* ptr to log operation header */
1795     __psint_t        ptr;            /* copy address into data region */
1796     int              len;            /* # xlog_write() bytes 2 still copy */
1797     int              index;          /* region index currently copying */
1798     int              log_offset;     /* offset (from 0) into data region */
1799     int              start_rec_copy; /* # bytes to copy for start record */
1800     int              partial_copy;   /* did we split a region? */
1801     int              partial_copy_len;/* # bytes copied if split region */
1802     int              need_copy;      /* # bytes need to memcpy this region */
1803     int              copy_len;       /* # bytes actually memcpy'ing */
1804     int              copy_off;       /* # bytes from entry start */
1805     int              contwr;         /* continued write of in-core log? */
1806     int              error;
1807     int              record_cnt = 0, data_cnt = 0;
1808
1809     partial_copy_len = partial_copy = 0;
1810
1811     /* Calculate potential maximum space.  Each region gets its own
1812      * xlog_op_header_t and may need to be double word aligned.
1813      */
1814     len = 0;
1815     if (ticket->t_flags & XLOG_TIC_INITED) {    /* acct for start rec of xact */
1816         len += sizeof(xlog_op_header_t);
1817         ticket->t_res_num_ophdrs++;
1818     }
1819
1820     for (index = 0; index < nentries; index++) {
1821         len += sizeof(xlog_op_header_t);            /* each region gets >= 1 */
1822         ticket->t_res_num_ophdrs++;
1823         len += reg[index].i_len;
1824         xlog_tic_add_region(ticket, reg[index].i_len, reg[index].i_type);
1825     }
1826     contwr = *start_lsn = 0;
1827
1828     if (ticket->t_curr_res < len) {
1829         xlog_print_tic_res(mp, ticket);
1830 #ifdef DEBUG
1831         xlog_panic(
1832                 "xfs_log_write: reservation ran out. Need to up reservation");
1833 #else
1834         /* Customer configurable panic */
1835         xfs_cmn_err(XFS_PTAG_LOGRES, CE_ALERT, mp,
1836                 "xfs_log_write: reservation ran out. Need to up reservation");
1837         /* If we did not panic, shutdown the filesystem */
1838         xfs_force_shutdown(mp, SHUTDOWN_CORRUPT_INCORE);
1839 #endif
1840     } else
1841         ticket->t_curr_res -= len;
1842
1843     for (index = 0; index < nentries; ) {
1844         if ((error = xlog_state_get_iclog_space(log, len, &iclog, ticket,
1845                                                &contwr, &log_offset)))
1846                 return error;
1847
1848         ASSERT(log_offset <= iclog->ic_size - 1);
1849         ptr = (__psint_t) ((char *)iclog->ic_datap+log_offset);
1850
1851         /* start_lsn is the first lsn written to. That's all we need. */
1852         if (! *start_lsn)
1853             *start_lsn = be64_to_cpu(iclog->ic_header.h_lsn);
1854
1855         /* This loop writes out as many regions as can fit in the amount
1856          * of space which was allocated by xlog_state_get_iclog_space().
1857          */
1858         while (index < nentries) {
1859             ASSERT(reg[index].i_len % sizeof(__int32_t) == 0);
1860             ASSERT((__psint_t)ptr % sizeof(__int32_t) == 0);
1861             start_rec_copy = 0;
1862
1863             /* If first write for transaction, insert start record.
1864              * We can't be trying to commit if we are inited.  We can't
1865              * have any "partial_copy" if we are inited.
1866              */
1867             if (ticket->t_flags & XLOG_TIC_INITED) {
1868                 logop_head              = (xlog_op_header_t *)ptr;
1869                 logop_head->oh_tid      = cpu_to_be32(ticket->t_tid);
1870                 logop_head->oh_clientid = ticket->t_clientid;
1871                 logop_head->oh_len      = 0;
1872                 logop_head->oh_flags    = XLOG_START_TRANS;
1873                 logop_head->oh_res2     = 0;
1874                 ticket->t_flags         &= ~XLOG_TIC_INITED;    /* clear bit */
1875                 record_cnt++;
1876
1877                 start_rec_copy = sizeof(xlog_op_header_t);
1878                 xlog_write_adv_cnt(ptr, len, log_offset, start_rec_copy);
1879             }
1880
1881             /* Copy log operation header directly into data section */
1882             logop_head                  = (xlog_op_header_t *)ptr;
1883             logop_head->oh_tid          = cpu_to_be32(ticket->t_tid);
1884             logop_head->oh_clientid     = ticket->t_clientid;
1885             logop_head->oh_res2         = 0;
1886
1887             /* header copied directly */
1888             xlog_write_adv_cnt(ptr, len, log_offset, sizeof(xlog_op_header_t));
1889
1890             /* are we copying a commit or unmount record? */
1891             logop_head->oh_flags = flags;
1892
1893             /*
1894              * We've seen logs corrupted with bad transaction client
1895              * ids.  This makes sure that XFS doesn't generate them on.
1896              * Turn this into an EIO and shut down the filesystem.
1897              */
1898             switch (logop_head->oh_clientid)  {
1899             case XFS_TRANSACTION:
1900             case XFS_VOLUME:
1901             case XFS_LOG:
1902                 break;
1903             default:
1904                 xfs_fs_cmn_err(CE_WARN, mp,
1905                     "Bad XFS transaction clientid 0x%x in ticket 0x%p",
1906                     logop_head->oh_clientid, tic);
1907                 return XFS_ERROR(EIO);
1908             }
1909
1910             /* Partial write last time? => (partial_copy != 0)
1911              * need_copy is the amount we'd like to copy if everything could
1912              * fit in the current memcpy.
1913              */
1914             need_copy = reg[index].i_len - partial_copy_len;
1915
1916             copy_off = partial_copy_len;
1917             if (need_copy <= iclog->ic_size - log_offset) { /*complete write */
1918                 copy_len = need_copy;
1919                 logop_head->oh_len = cpu_to_be32(copy_len);
1920                 if (partial_copy)
1921                     logop_head->oh_flags|= (XLOG_END_TRANS|XLOG_WAS_CONT_TRANS);
1922                 partial_copy_len = partial_copy = 0;
1923             } else {                                        /* partial write */
1924                 copy_len = iclog->ic_size - log_offset;
1925                 logop_head->oh_len = cpu_to_be32(copy_len);
1926                 logop_head->oh_flags |= XLOG_CONTINUE_TRANS;
1927                 if (partial_copy)
1928                         logop_head->oh_flags |= XLOG_WAS_CONT_TRANS;
1929                 partial_copy_len += copy_len;
1930                 partial_copy++;
1931                 len += sizeof(xlog_op_header_t); /* from splitting of region */
1932                 /* account for new log op header */
1933                 ticket->t_curr_res -= sizeof(xlog_op_header_t);
1934                 ticket->t_res_num_ophdrs++;
1935             }
1936             xlog_verify_dest_ptr(log, ptr);
1937
1938             /* copy region */
1939             ASSERT(copy_len >= 0);
1940             memcpy((xfs_caddr_t)ptr, reg[index].i_addr + copy_off, copy_len);
1941             xlog_write_adv_cnt(ptr, len, log_offset, copy_len);
1942
1943             /* make copy_len total bytes copied, including headers */
1944             copy_len += start_rec_copy + sizeof(xlog_op_header_t);
1945             record_cnt++;
1946             data_cnt += contwr ? copy_len : 0;
1947             if (partial_copy) {                 /* copied partial region */
1948                     /* already marked WANT_SYNC by xlog_state_get_iclog_space */
1949                     xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1950                     record_cnt = data_cnt = 0;
1951                     if ((error = xlog_state_release_iclog(log, iclog)))
1952                             return error;
1953                     break;                      /* don't increment index */
1954             } else {                            /* copied entire region */
1955                 index++;
1956                 partial_copy_len = partial_copy = 0;
1957
1958                 if (iclog->ic_size - log_offset <= sizeof(xlog_op_header_t)) {
1959                     xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1960                     record_cnt = data_cnt = 0;
1961                     xlog_state_want_sync(log, iclog);
1962                     if (commit_iclog) {
1963                         ASSERT(flags & XLOG_COMMIT_TRANS);
1964                         *commit_iclog = iclog;
1965                     } else if ((error = xlog_state_release_iclog(log, iclog)))
1966                            return error;
1967                     if (index == nentries)
1968                             return 0;           /* we are done */
1969                     else
1970                             break;
1971                 }
1972             } /* if (partial_copy) */
1973         } /* while (index < nentries) */
1974     } /* for (index = 0; index < nentries; ) */
1975     ASSERT(len == 0);
1976
1977     xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1978     if (commit_iclog) {
1979         ASSERT(flags & XLOG_COMMIT_TRANS);
1980         *commit_iclog = iclog;
1981         return 0;
1982     }
1983     return xlog_state_release_iclog(log, iclog);
1984 }       /* xlog_write */
1985
1986
1987 /*****************************************************************************
1988  *
1989  *              State Machine functions
1990  *
1991  *****************************************************************************
1992  */
1993
1994 /* Clean iclogs starting from the head.  This ordering must be
1995  * maintained, so an iclog doesn't become ACTIVE beyond one that
1996  * is SYNCING.  This is also required to maintain the notion that we use
1997  * a ordered wait queue to hold off would be writers to the log when every
1998  * iclog is trying to sync to disk.
1999  *
2000  * State Change: DIRTY -> ACTIVE
2001  */
2002 STATIC void
2003 xlog_state_clean_log(xlog_t *log)
2004 {
2005         xlog_in_core_t  *iclog;
2006         int changed = 0;
2007
2008         iclog = log->l_iclog;
2009         do {
2010                 if (iclog->ic_state == XLOG_STATE_DIRTY) {
2011                         iclog->ic_state = XLOG_STATE_ACTIVE;
2012                         iclog->ic_offset       = 0;
2013                         ASSERT(iclog->ic_callback == NULL);
2014                         /*
2015                          * If the number of ops in this iclog indicate it just
2016                          * contains the dummy transaction, we can
2017                          * change state into IDLE (the second time around).
2018                          * Otherwise we should change the state into
2019                          * NEED a dummy.
2020                          * We don't need to cover the dummy.
2021                          */
2022                         if (!changed &&
2023                            (be32_to_cpu(iclog->ic_header.h_num_logops) ==
2024                                         XLOG_COVER_OPS)) {
2025                                 changed = 1;
2026                         } else {
2027                                 /*
2028                                  * We have two dirty iclogs so start over
2029                                  * This could also be num of ops indicates
2030                                  * this is not the dummy going out.
2031                                  */
2032                                 changed = 2;
2033                         }
2034                         iclog->ic_header.h_num_logops = 0;
2035                         memset(iclog->ic_header.h_cycle_data, 0,
2036                               sizeof(iclog->ic_header.h_cycle_data));
2037                         iclog->ic_header.h_lsn = 0;
2038                 } else if (iclog->ic_state == XLOG_STATE_ACTIVE)
2039                         /* do nothing */;
2040                 else
2041                         break;  /* stop cleaning */
2042                 iclog = iclog->ic_next;
2043         } while (iclog != log->l_iclog);
2044
2045         /* log is locked when we are called */
2046         /*
2047          * Change state for the dummy log recording.
2048          * We usually go to NEED. But we go to NEED2 if the changed indicates
2049          * we are done writing the dummy record.
2050          * If we are done with the second dummy recored (DONE2), then
2051          * we go to IDLE.
2052          */
2053         if (changed) {
2054                 switch (log->l_covered_state) {
2055                 case XLOG_STATE_COVER_IDLE:
2056                 case XLOG_STATE_COVER_NEED:
2057                 case XLOG_STATE_COVER_NEED2:
2058                         log->l_covered_state = XLOG_STATE_COVER_NEED;
2059                         break;
2060
2061                 case XLOG_STATE_COVER_DONE:
2062                         if (changed == 1)
2063                                 log->l_covered_state = XLOG_STATE_COVER_NEED2;
2064                         else
2065                                 log->l_covered_state = XLOG_STATE_COVER_NEED;
2066                         break;
2067
2068                 case XLOG_STATE_COVER_DONE2:
2069                         if (changed == 1)
2070                                 log->l_covered_state = XLOG_STATE_COVER_IDLE;
2071                         else
2072                                 log->l_covered_state = XLOG_STATE_COVER_NEED;
2073                         break;
2074
2075                 default:
2076                         ASSERT(0);
2077                 }
2078         }
2079 }       /* xlog_state_clean_log */
2080
2081 STATIC xfs_lsn_t
2082 xlog_get_lowest_lsn(
2083         xlog_t          *log)
2084 {
2085         xlog_in_core_t  *lsn_log;
2086         xfs_lsn_t       lowest_lsn, lsn;
2087
2088         lsn_log = log->l_iclog;
2089         lowest_lsn = 0;
2090         do {
2091             if (!(lsn_log->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY))) {
2092                 lsn = be64_to_cpu(lsn_log->ic_header.h_lsn);
2093                 if ((lsn && !lowest_lsn) ||
2094                     (XFS_LSN_CMP(lsn, lowest_lsn) < 0)) {
2095                         lowest_lsn = lsn;
2096                 }
2097             }
2098             lsn_log = lsn_log->ic_next;
2099         } while (lsn_log != log->l_iclog);
2100         return lowest_lsn;
2101 }
2102
2103
2104 STATIC void
2105 xlog_state_do_callback(
2106         xlog_t          *log,
2107         int             aborted,
2108         xlog_in_core_t  *ciclog)
2109 {
2110         xlog_in_core_t     *iclog;
2111         xlog_in_core_t     *first_iclog;        /* used to know when we've
2112                                                  * processed all iclogs once */
2113         xfs_log_callback_t *cb, *cb_next;
2114         int                flushcnt = 0;
2115         xfs_lsn_t          lowest_lsn;
2116         int                ioerrors;    /* counter: iclogs with errors */
2117         int                loopdidcallbacks; /* flag: inner loop did callbacks*/
2118         int                funcdidcallbacks; /* flag: function did callbacks */
2119         int                repeats;     /* for issuing console warnings if
2120                                          * looping too many times */
2121         int                wake = 0;
2122
2123         spin_lock(&log->l_icloglock);
2124         first_iclog = iclog = log->l_iclog;
2125         ioerrors = 0;
2126         funcdidcallbacks = 0;
2127         repeats = 0;
2128
2129         do {
2130                 /*
2131                  * Scan all iclogs starting with the one pointed to by the
2132                  * log.  Reset this starting point each time the log is
2133                  * unlocked (during callbacks).
2134                  *
2135                  * Keep looping through iclogs until one full pass is made
2136                  * without running any callbacks.
2137                  */
2138                 first_iclog = log->l_iclog;
2139                 iclog = log->l_iclog;
2140                 loopdidcallbacks = 0;
2141                 repeats++;
2142
2143                 do {
2144
2145                         /* skip all iclogs in the ACTIVE & DIRTY states */
2146                         if (iclog->ic_state &
2147                             (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY)) {
2148                                 iclog = iclog->ic_next;
2149                                 continue;
2150                         }
2151
2152                         /*
2153                          * Between marking a filesystem SHUTDOWN and stopping
2154                          * the log, we do flush all iclogs to disk (if there
2155                          * wasn't a log I/O error). So, we do want things to
2156                          * go smoothly in case of just a SHUTDOWN  w/o a
2157                          * LOG_IO_ERROR.
2158                          */
2159                         if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
2160                                 /*
2161                                  * Can only perform callbacks in order.  Since
2162                                  * this iclog is not in the DONE_SYNC/
2163                                  * DO_CALLBACK state, we skip the rest and
2164                                  * just try to clean up.  If we set our iclog
2165                                  * to DO_CALLBACK, we will not process it when
2166                                  * we retry since a previous iclog is in the
2167                                  * CALLBACK and the state cannot change since
2168                                  * we are holding the l_icloglock.
2169                                  */
2170                                 if (!(iclog->ic_state &
2171                                         (XLOG_STATE_DONE_SYNC |
2172                                                  XLOG_STATE_DO_CALLBACK))) {
2173                                         if (ciclog && (ciclog->ic_state ==
2174                                                         XLOG_STATE_DONE_SYNC)) {
2175                                                 ciclog->ic_state = XLOG_STATE_DO_CALLBACK;
2176                                         }
2177                                         break;
2178                                 }
2179                                 /*
2180                                  * We now have an iclog that is in either the
2181                                  * DO_CALLBACK or DONE_SYNC states. The other
2182                                  * states (WANT_SYNC, SYNCING, or CALLBACK were
2183                                  * caught by the above if and are going to
2184                                  * clean (i.e. we aren't doing their callbacks)
2185                                  * see the above if.
2186                                  */
2187
2188                                 /*
2189                                  * We will do one more check here to see if we
2190                                  * have chased our tail around.
2191                                  */
2192
2193                                 lowest_lsn = xlog_get_lowest_lsn(log);
2194                                 if (lowest_lsn &&
2195                                     XFS_LSN_CMP(lowest_lsn,
2196                                                 be64_to_cpu(iclog->ic_header.h_lsn)) < 0) {
2197                                         iclog = iclog->ic_next;
2198                                         continue; /* Leave this iclog for
2199                                                    * another thread */
2200                                 }
2201
2202                                 iclog->ic_state = XLOG_STATE_CALLBACK;
2203
2204                                 spin_unlock(&log->l_icloglock);
2205
2206                                 /* l_last_sync_lsn field protected by
2207                                  * l_grant_lock. Don't worry about iclog's lsn.
2208                                  * No one else can be here except us.
2209                                  */
2210                                 spin_lock(&log->l_grant_lock);
2211                                 ASSERT(XFS_LSN_CMP(log->l_last_sync_lsn,
2212                                        be64_to_cpu(iclog->ic_header.h_lsn)) <= 0);
2213                                 log->l_last_sync_lsn =
2214                                         be64_to_cpu(iclog->ic_header.h_lsn);
2215                                 spin_unlock(&log->l_grant_lock);
2216
2217                         } else {
2218                                 spin_unlock(&log->l_icloglock);
2219                                 ioerrors++;
2220                         }
2221
2222                         /*
2223                          * Keep processing entries in the callback list until
2224                          * we come around and it is empty.  We need to
2225                          * atomically see that the list is empty and change the
2226                          * state to DIRTY so that we don't miss any more
2227                          * callbacks being added.
2228                          */
2229                         spin_lock(&iclog->ic_callback_lock);
2230                         cb = iclog->ic_callback;
2231                         while (cb) {
2232                                 iclog->ic_callback_tail = &(iclog->ic_callback);
2233                                 iclog->ic_callback = NULL;
2234                                 spin_unlock(&iclog->ic_callback_lock);
2235
2236                                 /* perform callbacks in the order given */
2237                                 for (; cb; cb = cb_next) {
2238                                         cb_next = cb->cb_next;
2239                                         cb->cb_func(cb->cb_arg, aborted);
2240                                 }
2241                                 spin_lock(&iclog->ic_callback_lock);
2242                                 cb = iclog->ic_callback;
2243                         }
2244
2245                         loopdidcallbacks++;
2246                         funcdidcallbacks++;
2247
2248                         spin_lock(&log->l_icloglock);
2249                         ASSERT(iclog->ic_callback == NULL);
2250                         spin_unlock(&iclog->ic_callback_lock);
2251                         if (!(iclog->ic_state & XLOG_STATE_IOERROR))
2252                                 iclog->ic_state = XLOG_STATE_DIRTY;
2253
2254                         /*
2255                          * Transition from DIRTY to ACTIVE if applicable.
2256                          * NOP if STATE_IOERROR.
2257                          */
2258                         xlog_state_clean_log(log);
2259
2260                         /* wake up threads waiting in xfs_log_force() */
2261                         sv_broadcast(&iclog->ic_force_wait);
2262
2263                         iclog = iclog->ic_next;
2264                 } while (first_iclog != iclog);
2265
2266                 if (repeats > 5000) {
2267                         flushcnt += repeats;
2268                         repeats = 0;
2269                         xfs_fs_cmn_err(CE_WARN, log->l_mp,
2270                                 "%s: possible infinite loop (%d iterations)",
2271                                 __func__, flushcnt);
2272                 }
2273         } while (!ioerrors && loopdidcallbacks);
2274
2275         /*
2276          * make one last gasp attempt to see if iclogs are being left in
2277          * limbo..
2278          */
2279 #ifdef DEBUG
2280         if (funcdidcallbacks) {
2281                 first_iclog = iclog = log->l_iclog;
2282                 do {
2283                         ASSERT(iclog->ic_state != XLOG_STATE_DO_CALLBACK);
2284                         /*
2285                          * Terminate the loop if iclogs are found in states
2286                          * which will cause other threads to clean up iclogs.
2287                          *
2288                          * SYNCING - i/o completion will go through logs
2289                          * DONE_SYNC - interrupt thread should be waiting for
2290                          *              l_icloglock
2291                          * IOERROR - give up hope all ye who enter here
2292                          */
2293                         if (iclog->ic_state == XLOG_STATE_WANT_SYNC ||
2294                             iclog->ic_state == XLOG_STATE_SYNCING ||
2295                             iclog->ic_state == XLOG_STATE_DONE_SYNC ||
2296                             iclog->ic_state == XLOG_STATE_IOERROR )
2297                                 break;
2298                         iclog = iclog->ic_next;
2299                 } while (first_iclog != iclog);
2300         }
2301 #endif
2302
2303         if (log->l_iclog->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_IOERROR))
2304                 wake = 1;
2305         spin_unlock(&log->l_icloglock);
2306
2307         if (wake)
2308                 sv_broadcast(&log->l_flush_wait);
2309 }
2310
2311
2312 /*
2313  * Finish transitioning this iclog to the dirty state.
2314  *
2315  * Make sure that we completely execute this routine only when this is
2316  * the last call to the iclog.  There is a good chance that iclog flushes,
2317  * when we reach the end of the physical log, get turned into 2 separate
2318  * calls to bwrite.  Hence, one iclog flush could generate two calls to this
2319  * routine.  By using the reference count bwritecnt, we guarantee that only
2320  * the second completion goes through.
2321  *
2322  * Callbacks could take time, so they are done outside the scope of the
2323  * global state machine log lock.
2324  */
2325 STATIC void
2326 xlog_state_done_syncing(
2327         xlog_in_core_t  *iclog,
2328         int             aborted)
2329 {
2330         xlog_t             *log = iclog->ic_log;
2331
2332         spin_lock(&log->l_icloglock);
2333
2334         ASSERT(iclog->ic_state == XLOG_STATE_SYNCING ||
2335                iclog->ic_state == XLOG_STATE_IOERROR);
2336         ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
2337         ASSERT(iclog->ic_bwritecnt == 1 || iclog->ic_bwritecnt == 2);
2338
2339
2340         /*
2341          * If we got an error, either on the first buffer, or in the case of
2342          * split log writes, on the second, we mark ALL iclogs STATE_IOERROR,
2343          * and none should ever be attempted to be written to disk
2344          * again.
2345          */
2346         if (iclog->ic_state != XLOG_STATE_IOERROR) {
2347                 if (--iclog->ic_bwritecnt == 1) {
2348                         spin_unlock(&log->l_icloglock);
2349                         return;
2350                 }
2351                 iclog->ic_state = XLOG_STATE_DONE_SYNC;
2352         }
2353
2354         /*
2355          * Someone could be sleeping prior to writing out the next
2356          * iclog buffer, we wake them all, one will get to do the
2357          * I/O, the others get to wait for the result.
2358          */
2359         sv_broadcast(&iclog->ic_write_wait);
2360         spin_unlock(&log->l_icloglock);
2361         xlog_state_do_callback(log, aborted, iclog);    /* also cleans log */
2362 }       /* xlog_state_done_syncing */
2363
2364
2365 /*
2366  * If the head of the in-core log ring is not (ACTIVE or DIRTY), then we must
2367  * sleep.  We wait on the flush queue on the head iclog as that should be
2368  * the first iclog to complete flushing. Hence if all iclogs are syncing,
2369  * we will wait here and all new writes will sleep until a sync completes.
2370  *
2371  * The in-core logs are used in a circular fashion. They are not used
2372  * out-of-order even when an iclog past the head is free.
2373  *
2374  * return:
2375  *      * log_offset where xlog_write() can start writing into the in-core
2376  *              log's data space.
2377  *      * in-core log pointer to which xlog_write() should write.
2378  *      * boolean indicating this is a continued write to an in-core log.
2379  *              If this is the last write, then the in-core log's offset field
2380  *              needs to be incremented, depending on the amount of data which
2381  *              is copied.
2382  */
2383 STATIC int
2384 xlog_state_get_iclog_space(xlog_t         *log,
2385                            int            len,
2386                            xlog_in_core_t **iclogp,
2387                            xlog_ticket_t  *ticket,
2388                            int            *continued_write,
2389                            int            *logoffsetp)
2390 {
2391         int               log_offset;
2392         xlog_rec_header_t *head;
2393         xlog_in_core_t    *iclog;
2394         int               error;
2395
2396 restart:
2397         spin_lock(&log->l_icloglock);
2398         if (XLOG_FORCED_SHUTDOWN(log)) {
2399                 spin_unlock(&log->l_icloglock);
2400                 return XFS_ERROR(EIO);
2401         }
2402
2403         iclog = log->l_iclog;
2404         if (iclog->ic_state != XLOG_STATE_ACTIVE) {
2405                 xlog_trace_iclog(iclog, XLOG_TRACE_SLEEP_FLUSH);
2406                 XFS_STATS_INC(xs_log_noiclogs);
2407
2408                 /* Wait for log writes to have flushed */
2409                 sv_wait(&log->l_flush_wait, 0, &log->l_icloglock, 0);
2410                 goto restart;
2411         }
2412
2413         head = &iclog->ic_header;
2414
2415         atomic_inc(&iclog->ic_refcnt);  /* prevents sync */
2416         log_offset = iclog->ic_offset;
2417
2418         /* On the 1st write to an iclog, figure out lsn.  This works
2419          * if iclogs marked XLOG_STATE_WANT_SYNC always write out what they are
2420          * committing to.  If the offset is set, that's how many blocks
2421          * must be written.
2422          */
2423         if (log_offset == 0) {
2424                 ticket->t_curr_res -= log->l_iclog_hsize;
2425                 xlog_tic_add_region(ticket,
2426                                     log->l_iclog_hsize,
2427                                     XLOG_REG_TYPE_LRHEADER);
2428                 head->h_cycle = cpu_to_be32(log->l_curr_cycle);
2429                 head->h_lsn = cpu_to_be64(
2430                         xlog_assign_lsn(log->l_curr_cycle, log->l_curr_block));
2431                 ASSERT(log->l_curr_block >= 0);
2432         }
2433
2434         /* If there is enough room to write everything, then do it.  Otherwise,
2435          * claim the rest of the region and make sure the XLOG_STATE_WANT_SYNC
2436          * bit is on, so this will get flushed out.  Don't update ic_offset
2437          * until you know exactly how many bytes get copied.  Therefore, wait
2438          * until later to update ic_offset.
2439          *
2440          * xlog_write() algorithm assumes that at least 2 xlog_op_header_t's
2441          * can fit into remaining data section.
2442          */
2443         if (iclog->ic_size - iclog->ic_offset < 2*sizeof(xlog_op_header_t)) {
2444                 xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2445
2446                 /*
2447                  * If I'm the only one writing to this iclog, sync it to disk.
2448                  * We need to do an atomic compare and decrement here to avoid
2449                  * racing with concurrent atomic_dec_and_lock() calls in
2450                  * xlog_state_release_iclog() when there is more than one
2451                  * reference to the iclog.
2452                  */
2453                 if (!atomic_add_unless(&iclog->ic_refcnt, -1, 1)) {
2454                         /* we are the only one */
2455                         spin_unlock(&log->l_icloglock);
2456                         error = xlog_state_release_iclog(log, iclog);
2457                         if (error)
2458                                 return error;
2459                 } else {
2460                         spin_unlock(&log->l_icloglock);
2461                 }
2462                 goto restart;
2463         }
2464
2465         /* Do we have enough room to write the full amount in the remainder
2466          * of this iclog?  Or must we continue a write on the next iclog and
2467          * mark this iclog as completely taken?  In the case where we switch
2468          * iclogs (to mark it taken), this particular iclog will release/sync
2469          * to disk in xlog_write().
2470          */
2471         if (len <= iclog->ic_size - iclog->ic_offset) {
2472                 *continued_write = 0;
2473                 iclog->ic_offset += len;
2474         } else {
2475                 *continued_write = 1;
2476                 xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2477         }
2478         *iclogp = iclog;
2479
2480         ASSERT(iclog->ic_offset <= iclog->ic_size);
2481         spin_unlock(&log->l_icloglock);
2482
2483         *logoffsetp = log_offset;
2484         return 0;
2485 }       /* xlog_state_get_iclog_space */
2486
2487 /*
2488  * Atomically get the log space required for a log ticket.
2489  *
2490  * Once a ticket gets put onto the reserveq, it will only return after
2491  * the needed reservation is satisfied.
2492  */
2493 STATIC int
2494 xlog_grant_log_space(xlog_t        *log,
2495                      xlog_ticket_t *tic)
2496 {
2497         int              free_bytes;
2498         int              need_bytes;
2499 #ifdef DEBUG
2500         xfs_lsn_t        tail_lsn;
2501 #endif
2502
2503
2504 #ifdef DEBUG
2505         if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2506                 panic("grant Recovery problem");
2507 #endif
2508
2509         /* Is there space or do we need to sleep? */
2510         spin_lock(&log->l_grant_lock);
2511         xlog_trace_loggrant(log, tic, "xlog_grant_log_space: enter");
2512
2513         /* something is already sleeping; insert new transaction at end */
2514         if (log->l_reserve_headq) {
2515                 xlog_ins_ticketq(&log->l_reserve_headq, tic);
2516                 xlog_trace_loggrant(log, tic,
2517                                     "xlog_grant_log_space: sleep 1");
2518                 /*
2519                  * Gotta check this before going to sleep, while we're
2520                  * holding the grant lock.
2521                  */
2522                 if (XLOG_FORCED_SHUTDOWN(log))
2523                         goto error_return;
2524
2525                 XFS_STATS_INC(xs_sleep_logspace);
2526                 sv_wait(&tic->t_wait, PINOD|PLTWAIT, &log->l_grant_lock, s);
2527                 /*
2528                  * If we got an error, and the filesystem is shutting down,
2529                  * we'll catch it down below. So just continue...
2530                  */
2531                 xlog_trace_loggrant(log, tic,
2532                                     "xlog_grant_log_space: wake 1");
2533                 spin_lock(&log->l_grant_lock);
2534         }
2535         if (tic->t_flags & XFS_LOG_PERM_RESERV)
2536                 need_bytes = tic->t_unit_res*tic->t_ocnt;
2537         else
2538                 need_bytes = tic->t_unit_res;
2539
2540 redo:
2541         if (XLOG_FORCED_SHUTDOWN(log))
2542                 goto error_return;
2543
2544         free_bytes = xlog_space_left(log, log->l_grant_reserve_cycle,
2545                                      log->l_grant_reserve_bytes);
2546         if (free_bytes < need_bytes) {
2547                 if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2548                         xlog_ins_ticketq(&log->l_reserve_headq, tic);
2549                 xlog_trace_loggrant(log, tic,
2550                                     "xlog_grant_log_space: sleep 2");
2551                 XFS_STATS_INC(xs_sleep_logspace);
2552                 sv_wait(&tic->t_wait, PINOD|PLTWAIT, &log->l_grant_lock, s);
2553
2554                 if (XLOG_FORCED_SHUTDOWN(log)) {
2555                         spin_lock(&log->l_grant_lock);
2556                         goto error_return;
2557                 }
2558
2559                 xlog_trace_loggrant(log, tic,
2560                                     "xlog_grant_log_space: wake 2");
2561                 xlog_grant_push_ail(log->l_mp, need_bytes);
2562                 spin_lock(&log->l_grant_lock);
2563                 goto redo;
2564         } else if (tic->t_flags & XLOG_TIC_IN_Q)
2565                 xlog_del_ticketq(&log->l_reserve_headq, tic);
2566
2567         /* we've got enough space */
2568         xlog_grant_add_space(log, need_bytes);
2569 #ifdef DEBUG
2570         tail_lsn = log->l_tail_lsn;
2571         /*
2572          * Check to make sure the grant write head didn't just over lap the
2573          * tail.  If the cycles are the same, we can't be overlapping.
2574          * Otherwise, make sure that the cycles differ by exactly one and
2575          * check the byte count.
2576          */
2577         if (CYCLE_LSN(tail_lsn) != log->l_grant_write_cycle) {
2578                 ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn));
2579                 ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn)));
2580         }
2581 #endif
2582         xlog_trace_loggrant(log, tic, "xlog_grant_log_space: exit");
2583         xlog_verify_grant_head(log, 1);
2584         spin_unlock(&log->l_grant_lock);
2585         return 0;
2586
2587  error_return:
2588         if (tic->t_flags & XLOG_TIC_IN_Q)
2589                 xlog_del_ticketq(&log->l_reserve_headq, tic);
2590         xlog_trace_loggrant(log, tic, "xlog_grant_log_space: err_ret");
2591         /*
2592          * If we are failing, make sure the ticket doesn't have any
2593          * current reservations. We don't want to add this back when
2594          * the ticket/transaction gets cancelled.
2595          */
2596         tic->t_curr_res = 0;
2597         tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2598         spin_unlock(&log->l_grant_lock);
2599         return XFS_ERROR(EIO);
2600 }       /* xlog_grant_log_space */
2601
2602
2603 /*
2604  * Replenish the byte reservation required by moving the grant write head.
2605  *
2606  *
2607  */
2608 STATIC int
2609 xlog_regrant_write_log_space(xlog_t        *log,
2610                              xlog_ticket_t *tic)
2611 {
2612         int             free_bytes, need_bytes;
2613         xlog_ticket_t   *ntic;
2614 #ifdef DEBUG
2615         xfs_lsn_t       tail_lsn;
2616 #endif
2617
2618         tic->t_curr_res = tic->t_unit_res;
2619         xlog_tic_reset_res(tic);
2620
2621         if (tic->t_cnt > 0)
2622                 return 0;
2623
2624 #ifdef DEBUG
2625         if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2626                 panic("regrant Recovery problem");
2627 #endif
2628
2629         spin_lock(&log->l_grant_lock);
2630         xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: enter");
2631
2632         if (XLOG_FORCED_SHUTDOWN(log))
2633                 goto error_return;
2634
2635         /* If there are other waiters on the queue then give them a
2636          * chance at logspace before us. Wake up the first waiters,
2637          * if we do not wake up all the waiters then go to sleep waiting
2638          * for more free space, otherwise try to get some space for
2639          * this transaction.
2640          */
2641
2642         if ((ntic = log->l_write_headq)) {
2643                 free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2644                                              log->l_grant_write_bytes);
2645                 do {
2646                         ASSERT(ntic->t_flags & XLOG_TIC_PERM_RESERV);
2647
2648                         if (free_bytes < ntic->t_unit_res)
2649                                 break;
2650                         free_bytes -= ntic->t_unit_res;
2651                         sv_signal(&ntic->t_wait);
2652                         ntic = ntic->t_next;
2653                 } while (ntic != log->l_write_headq);
2654
2655                 if (ntic != log->l_write_headq) {
2656                         if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2657                                 xlog_ins_ticketq(&log->l_write_headq, tic);
2658
2659                         xlog_trace_loggrant(log, tic,
2660                                     "xlog_regrant_write_log_space: sleep 1");
2661                         XFS_STATS_INC(xs_sleep_logspace);
2662                         sv_wait(&tic->t_wait, PINOD|PLTWAIT,
2663                                 &log->l_grant_lock, s);
2664
2665                         /* If we're shutting down, this tic is already
2666                          * off the queue */
2667                         if (XLOG_FORCED_SHUTDOWN(log)) {
2668                                 spin_lock(&log->l_grant_lock);
2669                                 goto error_return;
2670                         }
2671
2672                         xlog_trace_loggrant(log, tic,
2673                                     "xlog_regrant_write_log_space: wake 1");
2674                         xlog_grant_push_ail(log->l_mp, tic->t_unit_res);
2675                         spin_lock(&log->l_grant_lock);
2676                 }
2677         }
2678
2679         need_bytes = tic->t_unit_res;
2680
2681 redo:
2682         if (XLOG_FORCED_SHUTDOWN(log))
2683                 goto error_return;
2684
2685         free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2686                                      log->l_grant_write_bytes);
2687         if (free_bytes < need_bytes) {
2688                 if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2689                         xlog_ins_ticketq(&log->l_write_headq, tic);
2690                 XFS_STATS_INC(xs_sleep_logspace);
2691                 sv_wait(&tic->t_wait, PINOD|PLTWAIT, &log->l_grant_lock, s);
2692
2693                 /* If we're shutting down, this tic is already off the queue */
2694                 if (XLOG_FORCED_SHUTDOWN(log)) {
2695                         spin_lock(&log->l_grant_lock);
2696                         goto error_return;
2697                 }
2698
2699                 xlog_trace_loggrant(log, tic,
2700                                     "xlog_regrant_write_log_space: wake 2");
2701                 xlog_grant_push_ail(log->l_mp, need_bytes);
2702                 spin_lock(&log->l_grant_lock);
2703                 goto redo;
2704         } else if (tic->t_flags & XLOG_TIC_IN_Q)
2705                 xlog_del_ticketq(&log->l_write_headq, tic);
2706
2707         /* we've got enough space */
2708         xlog_grant_add_space_write(log, need_bytes);
2709 #ifdef DEBUG
2710         tail_lsn = log->l_tail_lsn;
2711         if (CYCLE_LSN(tail_lsn) != log->l_grant_write_cycle) {
2712                 ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn));
2713                 ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn)));
2714         }
2715 #endif
2716
2717         xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: exit");
2718         xlog_verify_grant_head(log, 1);
2719         spin_unlock(&log->l_grant_lock);
2720         return 0;
2721
2722
2723  error_return:
2724         if (tic->t_flags & XLOG_TIC_IN_Q)
2725                 xlog_del_ticketq(&log->l_reserve_headq, tic);
2726         xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: err_ret");
2727         /*
2728          * If we are failing, make sure the ticket doesn't have any
2729          * current reservations. We don't want to add this back when
2730          * the ticket/transaction gets cancelled.
2731          */
2732         tic->t_curr_res = 0;
2733         tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2734         spin_unlock(&log->l_grant_lock);
2735         return XFS_ERROR(EIO);
2736 }       /* xlog_regrant_write_log_space */
2737
2738
2739 /* The first cnt-1 times through here we don't need to
2740  * move the grant write head because the permanent
2741  * reservation has reserved cnt times the unit amount.
2742  * Release part of current permanent unit reservation and
2743  * reset current reservation to be one units worth.  Also
2744  * move grant reservation head forward.
2745  */
2746 STATIC void
2747 xlog_regrant_reserve_log_space(xlog_t        *log,
2748                                xlog_ticket_t *ticket)
2749 {
2750         xlog_trace_loggrant(log, ticket,
2751                             "xlog_regrant_reserve_log_space: enter");
2752         if (ticket->t_cnt > 0)
2753                 ticket->t_cnt--;
2754
2755         spin_lock(&log->l_grant_lock);
2756         xlog_grant_sub_space(log, ticket->t_curr_res);
2757         ticket->t_curr_res = ticket->t_unit_res;
2758         xlog_tic_reset_res(ticket);
2759         xlog_trace_loggrant(log, ticket,
2760                             "xlog_regrant_reserve_log_space: sub current res");
2761         xlog_verify_grant_head(log, 1);
2762
2763         /* just return if we still have some of the pre-reserved space */
2764         if (ticket->t_cnt > 0) {
2765                 spin_unlock(&log->l_grant_lock);
2766                 return;
2767         }
2768
2769         xlog_grant_add_space_reserve(log, ticket->t_unit_res);
2770         xlog_trace_loggrant(log, ticket,
2771                             "xlog_regrant_reserve_log_space: exit");
2772         xlog_verify_grant_head(log, 0);
2773         spin_unlock(&log->l_grant_lock);
2774         ticket->t_curr_res = ticket->t_unit_res;
2775         xlog_tic_reset_res(ticket);
2776 }       /* xlog_regrant_reserve_log_space */
2777
2778
2779 /*
2780  * Give back the space left from a reservation.
2781  *
2782  * All the information we need to make a correct determination of space left
2783  * is present.  For non-permanent reservations, things are quite easy.  The
2784  * count should have been decremented to zero.  We only need to deal with the
2785  * space remaining in the current reservation part of the ticket.  If the
2786  * ticket contains a permanent reservation, there may be left over space which
2787  * needs to be released.  A count of N means that N-1 refills of the current
2788  * reservation can be done before we need to ask for more space.  The first
2789  * one goes to fill up the first current reservation.  Once we run out of
2790  * space, the count will stay at zero and the only space remaining will be
2791  * in the current reservation field.
2792  */
2793 STATIC void
2794 xlog_ungrant_log_space(xlog_t        *log,
2795                        xlog_ticket_t *ticket)
2796 {
2797         if (ticket->t_cnt > 0)
2798                 ticket->t_cnt--;
2799
2800         spin_lock(&log->l_grant_lock);
2801         xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: enter");
2802
2803         xlog_grant_sub_space(log, ticket->t_curr_res);
2804
2805         xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: sub current");
2806
2807         /* If this is a permanent reservation ticket, we may be able to free
2808          * up more space based on the remaining count.
2809          */
2810         if (ticket->t_cnt > 0) {
2811                 ASSERT(ticket->t_flags & XLOG_TIC_PERM_RESERV);
2812                 xlog_grant_sub_space(log, ticket->t_unit_res*ticket->t_cnt);
2813         }
2814
2815         xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: exit");
2816         xlog_verify_grant_head(log, 1);
2817         spin_unlock(&log->l_grant_lock);
2818         xfs_log_move_tail(log->l_mp, 1);
2819 }       /* xlog_ungrant_log_space */
2820
2821
2822 /*
2823  * Flush iclog to disk if this is the last reference to the given iclog and
2824  * the WANT_SYNC bit is set.
2825  *
2826  * When this function is entered, the iclog is not necessarily in the
2827  * WANT_SYNC state.  It may be sitting around waiting to get filled.
2828  *
2829  *
2830  */
2831 STATIC int
2832 xlog_state_release_iclog(
2833         xlog_t          *log,
2834         xlog_in_core_t  *iclog)
2835 {
2836         int             sync = 0;       /* do we sync? */
2837
2838         if (iclog->ic_state & XLOG_STATE_IOERROR)
2839                 return XFS_ERROR(EIO);
2840
2841         ASSERT(atomic_read(&iclog->ic_refcnt) > 0);
2842         if (!atomic_dec_and_lock(&iclog->ic_refcnt, &log->l_icloglock))
2843                 return 0;
2844
2845         if (iclog->ic_state & XLOG_STATE_IOERROR) {
2846                 spin_unlock(&log->l_icloglock);
2847                 return XFS_ERROR(EIO);
2848         }
2849         ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE ||
2850                iclog->ic_state == XLOG_STATE_WANT_SYNC);
2851
2852         if (iclog->ic_state == XLOG_STATE_WANT_SYNC) {
2853                 /* update tail before writing to iclog */
2854                 xlog_assign_tail_lsn(log->l_mp);
2855                 sync++;
2856                 iclog->ic_state = XLOG_STATE_SYNCING;
2857                 iclog->ic_header.h_tail_lsn = cpu_to_be64(log->l_tail_lsn);
2858                 xlog_verify_tail_lsn(log, iclog, log->l_tail_lsn);
2859                 /* cycle incremented when incrementing curr_block */
2860         }
2861         spin_unlock(&log->l_icloglock);
2862
2863         /*
2864          * We let the log lock go, so it's possible that we hit a log I/O
2865          * error or some other SHUTDOWN condition that marks the iclog
2866          * as XLOG_STATE_IOERROR before the bwrite. However, we know that
2867          * this iclog has consistent data, so we ignore IOERROR
2868          * flags after this point.
2869          */
2870         if (sync)
2871                 return xlog_sync(log, iclog);
2872         return 0;
2873 }       /* xlog_state_release_iclog */
2874
2875
2876 /*
2877  * This routine will mark the current iclog in the ring as WANT_SYNC
2878  * and move the current iclog pointer to the next iclog in the ring.
2879  * When this routine is called from xlog_state_get_iclog_space(), the
2880  * exact size of the iclog has not yet been determined.  All we know is
2881  * that every data block.  We have run out of space in this log record.
2882  */
2883 STATIC void
2884 xlog_state_switch_iclogs(xlog_t         *log,
2885                          xlog_in_core_t *iclog,
2886                          int            eventual_size)
2887 {
2888         ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
2889         if (!eventual_size)
2890                 eventual_size = iclog->ic_offset;
2891         iclog->ic_state = XLOG_STATE_WANT_SYNC;
2892         iclog->ic_header.h_prev_block = cpu_to_be32(log->l_prev_block);
2893         log->l_prev_block = log->l_curr_block;
2894         log->l_prev_cycle = log->l_curr_cycle;
2895
2896         /* roll log?: ic_offset changed later */
2897         log->l_curr_block += BTOBB(eventual_size)+BTOBB(log->l_iclog_hsize);
2898
2899         /* Round up to next log-sunit */
2900         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb) &&
2901             log->l_mp->m_sb.sb_logsunit > 1) {
2902                 __uint32_t sunit_bb = BTOBB(log->l_mp->m_sb.sb_logsunit);
2903                 log->l_curr_block = roundup(log->l_curr_block, sunit_bb);
2904         }
2905
2906         if (log->l_curr_block >= log->l_logBBsize) {
2907                 log->l_curr_cycle++;
2908                 if (log->l_curr_cycle == XLOG_HEADER_MAGIC_NUM)
2909                         log->l_curr_cycle++;
2910                 log->l_curr_block -= log->l_logBBsize;
2911                 ASSERT(log->l_curr_block >= 0);
2912         }
2913         ASSERT(iclog == log->l_iclog);
2914         log->l_iclog = iclog->ic_next;
2915 }       /* xlog_state_switch_iclogs */
2916
2917
2918 /*
2919  * Write out all data in the in-core log as of this exact moment in time.
2920  *
2921  * Data may be written to the in-core log during this call.  However,
2922  * we don't guarantee this data will be written out.  A change from past
2923  * implementation means this routine will *not* write out zero length LRs.
2924  *
2925  * Basically, we try and perform an intelligent scan of the in-core logs.
2926  * If we determine there is no flushable data, we just return.  There is no
2927  * flushable data if:
2928  *
2929  *      1. the current iclog is active and has no data; the previous iclog
2930  *              is in the active or dirty state.
2931  *      2. the current iclog is drity, and the previous iclog is in the
2932  *              active or dirty state.
2933  *
2934  * We may sleep if:
2935  *
2936  *      1. the current iclog is not in the active nor dirty state.
2937  *      2. the current iclog dirty, and the previous iclog is not in the
2938  *              active nor dirty state.
2939  *      3. the current iclog is active, and there is another thread writing
2940  *              to this particular iclog.
2941  *      4. a) the current iclog is active and has no other writers
2942  *         b) when we return from flushing out this iclog, it is still
2943  *              not in the active nor dirty state.
2944  */
2945 STATIC int
2946 xlog_state_sync_all(xlog_t *log, uint flags, int *log_flushed)
2947 {
2948         xlog_in_core_t  *iclog;
2949         xfs_lsn_t       lsn;
2950
2951         spin_lock(&log->l_icloglock);
2952
2953         iclog = log->l_iclog;
2954         if (iclog->ic_state & XLOG_STATE_IOERROR) {
2955                 spin_unlock(&log->l_icloglock);
2956                 return XFS_ERROR(EIO);
2957         }
2958
2959         /* If the head iclog is not active nor dirty, we just attach
2960          * ourselves to the head and go to sleep.
2961          */
2962         if (iclog->ic_state == XLOG_STATE_ACTIVE ||
2963             iclog->ic_state == XLOG_STATE_DIRTY) {
2964                 /*
2965                  * If the head is dirty or (active and empty), then
2966                  * we need to look at the previous iclog.  If the previous
2967                  * iclog is active or dirty we are done.  There is nothing
2968                  * to sync out.  Otherwise, we attach ourselves to the
2969                  * previous iclog and go to sleep.
2970                  */
2971                 if (iclog->ic_state == XLOG_STATE_DIRTY ||
2972                     (atomic_read(&iclog->ic_refcnt) == 0
2973                      && iclog->ic_offset == 0)) {
2974                         iclog = iclog->ic_prev;
2975                         if (iclog->ic_state == XLOG_STATE_ACTIVE ||
2976                             iclog->ic_state == XLOG_STATE_DIRTY)
2977                                 goto no_sleep;
2978                         else
2979                                 goto maybe_sleep;
2980                 } else {
2981                         if (atomic_read(&iclog->ic_refcnt) == 0) {
2982                                 /* We are the only one with access to this
2983                                  * iclog.  Flush it out now.  There should
2984                                  * be a roundoff of zero to show that someone
2985                                  * has already taken care of the roundoff from
2986                                  * the previous sync.
2987                                  */
2988                                 atomic_inc(&iclog->ic_refcnt);
2989                                 lsn = be64_to_cpu(iclog->ic_header.h_lsn);
2990                                 xlog_state_switch_iclogs(log, iclog, 0);
2991                                 spin_unlock(&log->l_icloglock);
2992
2993                                 if (xlog_state_release_iclog(log, iclog))
2994                                         return XFS_ERROR(EIO);
2995                                 *log_flushed = 1;
2996                                 spin_lock(&log->l_icloglock);
2997                                 if (be64_to_cpu(iclog->ic_header.h_lsn) == lsn &&
2998                                     iclog->ic_state != XLOG_STATE_DIRTY)
2999                                         goto maybe_sleep;
3000                                 else
3001                                         goto no_sleep;
3002                         } else {
3003                                 /* Someone else is writing to this iclog.
3004                                  * Use its call to flush out the data.  However,
3005                                  * the other thread may not force out this LR,
3006                                  * so we mark it WANT_SYNC.
3007                                  */
3008                                 xlog_state_switch_iclogs(log, iclog, 0);
3009                                 goto maybe_sleep;
3010                         }
3011                 }
3012         }
3013
3014         /* By the time we come around again, the iclog could've been filled
3015          * which would give it another lsn.  If we have a new lsn, just
3016          * return because the relevant data has been flushed.
3017          */
3018 maybe_sleep:
3019         if (flags & XFS_LOG_SYNC) {
3020                 /*
3021                  * We must check if we're shutting down here, before
3022                  * we wait, while we're holding the l_icloglock.
3023                  * Then we check again after waking up, in case our
3024                  * sleep was disturbed by a bad news.
3025                  */
3026                 if (iclog->ic_state & XLOG_STATE_IOERROR) {
3027                         spin_unlock(&log->l_icloglock);
3028                         return XFS_ERROR(EIO);
3029                 }
3030                 XFS_STATS_INC(xs_log_force_sleep);
3031                 sv_wait(&iclog->ic_force_wait, PINOD, &log->l_icloglock, s);
3032                 /*
3033                  * No need to grab the log lock here since we're
3034                  * only deciding whether or not to return EIO
3035                  * and the memory read should be atomic.
3036                  */
3037                 if (iclog->ic_state & XLOG_STATE_IOERROR)
3038                         return XFS_ERROR(EIO);
3039                 *log_flushed = 1;
3040
3041         } else {
3042
3043 no_sleep:
3044                 spin_unlock(&log->l_icloglock);
3045         }
3046         return 0;
3047 }       /* xlog_state_sync_all */
3048
3049
3050 /*
3051  * Used by code which implements synchronous log forces.
3052  *
3053  * Find in-core log with lsn.
3054  *      If it is in the DIRTY state, just return.
3055  *      If it is in the ACTIVE state, move the in-core log into the WANT_SYNC
3056  *              state and go to sleep or return.
3057  *      If it is in any other state, go to sleep or return.
3058  *
3059  * If filesystem activity goes to zero, the iclog will get flushed only by
3060  * bdflush().
3061  */
3062 STATIC int
3063 xlog_state_sync(xlog_t    *log,
3064                 xfs_lsn_t lsn,
3065                 uint      flags,
3066                 int       *log_flushed)
3067 {
3068     xlog_in_core_t      *iclog;
3069     int                 already_slept = 0;
3070
3071 try_again:
3072     spin_lock(&log->l_icloglock);
3073     iclog = log->l_iclog;
3074
3075     if (iclog->ic_state & XLOG_STATE_IOERROR) {
3076             spin_unlock(&log->l_icloglock);
3077             return XFS_ERROR(EIO);
3078     }
3079
3080     do {
3081         if (be64_to_cpu(iclog->ic_header.h_lsn) != lsn) {
3082                 iclog = iclog->ic_next;
3083                 continue;
3084         }
3085
3086         if (iclog->ic_state == XLOG_STATE_DIRTY) {
3087                 spin_unlock(&log->l_icloglock);
3088                 return 0;
3089         }
3090
3091         if (iclog->ic_state == XLOG_STATE_ACTIVE) {
3092                 /*
3093                  * We sleep here if we haven't already slept (e.g.
3094                  * this is the first time we've looked at the correct
3095                  * iclog buf) and the buffer before us is going to
3096                  * be sync'ed. The reason for this is that if we
3097                  * are doing sync transactions here, by waiting for
3098                  * the previous I/O to complete, we can allow a few
3099                  * more transactions into this iclog before we close
3100                  * it down.
3101                  *
3102                  * Otherwise, we mark the buffer WANT_SYNC, and bump
3103                  * up the refcnt so we can release the log (which drops
3104                  * the ref count).  The state switch keeps new transaction
3105                  * commits from using this buffer.  When the current commits
3106                  * finish writing into the buffer, the refcount will drop to
3107                  * zero and the buffer will go out then.
3108                  */
3109                 if (!already_slept &&
3110                     (iclog->ic_prev->ic_state & (XLOG_STATE_WANT_SYNC |
3111                                                  XLOG_STATE_SYNCING))) {
3112                         ASSERT(!(iclog->ic_state & XLOG_STATE_IOERROR));
3113                         XFS_STATS_INC(xs_log_force_sleep);
3114                         sv_wait(&iclog->ic_prev->ic_write_wait, PSWP,
3115                                 &log->l_icloglock, s);
3116                         *log_flushed = 1;
3117                         already_slept = 1;
3118                         goto try_again;
3119                 } else {
3120                         atomic_inc(&iclog->ic_refcnt);
3121                         xlog_state_switch_iclogs(log, iclog, 0);
3122                         spin_unlock(&log->l_icloglock);
3123                         if (xlog_state_release_iclog(log, iclog))
3124                                 return XFS_ERROR(EIO);
3125                         *log_flushed = 1;
3126                         spin_lock(&log->l_icloglock);
3127                 }
3128         }
3129
3130         if ((flags & XFS_LOG_SYNC) && /* sleep */
3131             !(iclog->ic_state & (XLOG_STATE_ACTIVE | XLOG_STATE_DIRTY))) {
3132
3133                 /*
3134                  * Don't wait on completion if we know that we've
3135                  * gotten a log write error.
3136                  */
3137                 if (iclog->ic_state & XLOG_STATE_IOERROR) {
3138                         spin_unlock(&log->l_icloglock);
3139                         return XFS_ERROR(EIO);
3140                 }
3141                 XFS_STATS_INC(xs_log_force_sleep);
3142                 sv_wait(&iclog->ic_force_wait, PSWP, &log->l_icloglock, s);
3143                 /*
3144                  * No need to grab the log lock here since we're
3145                  * only deciding whether or not to return EIO
3146                  * and the memory read should be atomic.
3147                  */
3148                 if (iclog->ic_state & XLOG_STATE_IOERROR)
3149                         return XFS_ERROR(EIO);
3150                 *log_flushed = 1;
3151         } else {                /* just return */
3152                 spin_unlock(&log->l_icloglock);
3153         }
3154         return 0;
3155
3156     } while (iclog != log->l_iclog);
3157
3158     spin_unlock(&log->l_icloglock);
3159     return 0;
3160 }       /* xlog_state_sync */
3161
3162
3163 /*
3164  * Called when we want to mark the current iclog as being ready to sync to
3165  * disk.
3166  */
3167 STATIC void
3168 xlog_state_want_sync(xlog_t *log, xlog_in_core_t *iclog)
3169 {
3170         spin_lock(&log->l_icloglock);
3171
3172         if (iclog->ic_state == XLOG_STATE_ACTIVE) {
3173                 xlog_state_switch_iclogs(log, iclog, 0);
3174         } else {
3175                 ASSERT(iclog->ic_state &
3176                         (XLOG_STATE_WANT_SYNC|XLOG_STATE_IOERROR));
3177         }
3178
3179         spin_unlock(&log->l_icloglock);
3180 }       /* xlog_state_want_sync */
3181
3182
3183
3184 /*****************************************************************************
3185  *
3186  *              TICKET functions
3187  *
3188  *****************************************************************************
3189  */
3190
3191 /*
3192  * Free a used ticket.
3193  */
3194 STATIC void
3195 xlog_ticket_put(xlog_t          *log,
3196                 xlog_ticket_t   *ticket)
3197 {
3198         sv_destroy(&ticket->t_wait);
3199         kmem_zone_free(xfs_log_ticket_zone, ticket);
3200 }       /* xlog_ticket_put */
3201
3202
3203 /*
3204  * Allocate and initialise a new log ticket.
3205  */
3206 STATIC xlog_ticket_t *
3207 xlog_ticket_get(xlog_t          *log,
3208                 int             unit_bytes,
3209                 int             cnt,
3210                 char            client,
3211                 uint            xflags)
3212 {
3213         xlog_ticket_t   *tic;
3214         uint            num_headers;
3215
3216         tic = kmem_zone_zalloc(xfs_log_ticket_zone, KM_SLEEP|KM_MAYFAIL);
3217         if (!tic)
3218                 return NULL;
3219
3220         /*
3221          * Permanent reservations have up to 'cnt'-1 active log operations
3222          * in the log.  A unit in this case is the amount of space for one
3223          * of these log operations.  Normal reservations have a cnt of 1
3224          * and their unit amount is the total amount of space required.
3225          *
3226          * The following lines of code account for non-transaction data
3227          * which occupy space in the on-disk log.
3228          *
3229          * Normal form of a transaction is:
3230          * <oph><trans-hdr><start-oph><reg1-oph><reg1><reg2-oph>...<commit-oph>
3231          * and then there are LR hdrs, split-recs and roundoff at end of syncs.
3232          *
3233          * We need to account for all the leadup data and trailer data
3234          * around the transaction data.
3235          * And then we need to account for the worst case in terms of using
3236          * more space.
3237          * The worst case will happen if:
3238          * - the placement of the transaction happens to be such that the
3239          *   roundoff is at its maximum
3240          * - the transaction data is synced before the commit record is synced
3241          *   i.e. <transaction-data><roundoff> | <commit-rec><roundoff>
3242          *   Therefore the commit record is in its own Log Record.
3243          *   This can happen as the commit record is called with its
3244          *   own region to xlog_write().
3245          *   This then means that in the worst case, roundoff can happen for
3246          *   the commit-rec as well.
3247          *   The commit-rec is smaller than padding in this scenario and so it is
3248          *   not added separately.
3249          */
3250
3251         /* for trans header */
3252         unit_bytes += sizeof(xlog_op_header_t);
3253         unit_bytes += sizeof(xfs_trans_header_t);
3254
3255         /* for start-rec */
3256         unit_bytes += sizeof(xlog_op_header_t);
3257
3258         /* for LR headers */
3259         num_headers = ((unit_bytes + log->l_iclog_size-1) >> log->l_iclog_size_log);
3260         unit_bytes += log->l_iclog_hsize * num_headers;
3261
3262         /* for commit-rec LR header - note: padding will subsume the ophdr */
3263         unit_bytes += log->l_iclog_hsize;
3264
3265         /* for split-recs - ophdrs added when data split over LRs */
3266         unit_bytes += sizeof(xlog_op_header_t) * num_headers;
3267
3268         /* for roundoff padding for transaction data and one for commit record */
3269         if (xfs_sb_version_haslogv2(&log->l_mp->m_sb) &&
3270             log->l_mp->m_sb.sb_logsunit > 1) {
3271                 /* log su roundoff */
3272                 unit_bytes += 2*log->l_mp->m_sb.sb_logsunit;
3273         } else {
3274                 /* BB roundoff */
3275                 unit_bytes += 2*BBSIZE;
3276         }
3277
3278         tic->t_unit_res         = unit_bytes;
3279         tic->t_curr_res         = unit_bytes;
3280         tic->t_cnt              = cnt;
3281         tic->t_ocnt             = cnt;
3282         tic->t_tid              = (xlog_tid_t)((__psint_t)tic & 0xffffffff);
3283         tic->t_clientid         = client;
3284         tic->t_flags            = XLOG_TIC_INITED;
3285         tic->t_trans_type       = 0;
3286         if (xflags & XFS_LOG_PERM_RESERV)
3287                 tic->t_flags |= XLOG_TIC_PERM_RESERV;
3288         sv_init(&(tic->t_wait), SV_DEFAULT, "logtick");
3289
3290         xlog_tic_reset_res(tic);
3291
3292         return tic;
3293 }       /* xlog_ticket_get */
3294
3295
3296 /******************************************************************************
3297  *
3298  *              Log debug routines
3299  *
3300  ******************************************************************************
3301  */
3302 #if defined(DEBUG)
3303 /*
3304  * Make sure that the destination ptr is within the valid data region of
3305  * one of the iclogs.  This uses backup pointers stored in a different
3306  * part of the log in case we trash the log structure.
3307  */
3308 void
3309 xlog_verify_dest_ptr(xlog_t     *log,
3310                      __psint_t  ptr)
3311 {
3312         int i;
3313         int good_ptr = 0;
3314
3315         for (i=0; i < log->l_iclog_bufs; i++) {
3316                 if (ptr >= (__psint_t)log->l_iclog_bak[i] &&
3317                     ptr <= (__psint_t)log->l_iclog_bak[i]+log->l_iclog_size)
3318                         good_ptr++;
3319         }
3320         if (! good_ptr)
3321                 xlog_panic("xlog_verify_dest_ptr: invalid ptr");
3322 }       /* xlog_verify_dest_ptr */
3323
3324 STATIC void
3325 xlog_verify_grant_head(xlog_t *log, int equals)
3326 {
3327     if (log->l_grant_reserve_cycle == log->l_grant_write_cycle) {
3328         if (equals)
3329             ASSERT(log->l_grant_reserve_bytes >= log->l_grant_write_bytes);
3330         else
3331             ASSERT(log->l_grant_reserve_bytes > log->l_grant_write_bytes);
3332     } else {
3333         ASSERT(log->l_grant_reserve_cycle-1 == log->l_grant_write_cycle);
3334         ASSERT(log->l_grant_write_bytes >= log->l_grant_reserve_bytes);
3335     }
3336 }       /* xlog_verify_grant_head */
3337
3338 /* check if it will fit */
3339 STATIC void
3340 xlog_verify_tail_lsn(xlog_t         *log,
3341                      xlog_in_core_t *iclog,
3342                      xfs_lsn_t      tail_lsn)
3343 {
3344     int blocks;
3345
3346     if (CYCLE_LSN(tail_lsn) == log->l_prev_cycle) {
3347         blocks =
3348             log->l_logBBsize - (log->l_prev_block - BLOCK_LSN(tail_lsn));
3349         if (blocks < BTOBB(iclog->ic_offset)+BTOBB(log->l_iclog_hsize))
3350             xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3351     } else {
3352         ASSERT(CYCLE_LSN(tail_lsn)+1 == log->l_prev_cycle);
3353
3354         if (BLOCK_LSN(tail_lsn) == log->l_prev_block)
3355             xlog_panic("xlog_verify_tail_lsn: tail wrapped");
3356
3357         blocks = BLOCK_LSN(tail_lsn) - log->l_prev_block;
3358         if (blocks < BTOBB(iclog->ic_offset) + 1)
3359             xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3360     }
3361 }       /* xlog_verify_tail_lsn */
3362
3363 /*
3364  * Perform a number of checks on the iclog before writing to disk.
3365  *
3366  * 1. Make sure the iclogs are still circular
3367  * 2. Make sure we have a good magic number
3368  * 3. Make sure we don't have magic numbers in the data
3369  * 4. Check fields of each log operation header for:
3370  *      A. Valid client identifier
3371  *      B. tid ptr value falls in valid ptr space (user space code)
3372  *      C. Length in log record header is correct according to the
3373  *              individual operation headers within record.
3374  * 5. When a bwrite will occur within 5 blocks of the front of the physical
3375  *      log, check the preceding blocks of the physical log to make sure all
3376  *      the cycle numbers agree with the current cycle number.
3377  */
3378 STATIC void
3379 xlog_verify_iclog(xlog_t         *log,
3380                   xlog_in_core_t *iclog,
3381                   int            count,
3382                   boolean_t      syncing)
3383 {
3384         xlog_op_header_t        *ophead;
3385         xlog_in_core_t          *icptr;
3386         xlog_in_core_2_t        *xhdr;
3387         xfs_caddr_t             ptr;
3388         xfs_caddr_t             base_ptr;
3389         __psint_t               field_offset;
3390         __uint8_t               clientid;
3391         int                     len, i, j, k, op_len;
3392         int                     idx;
3393
3394         /* check validity of iclog pointers */
3395         spin_lock(&log->l_icloglock);
3396         icptr = log->l_iclog;
3397         for (i=0; i < log->l_iclog_bufs; i++) {
3398                 if (icptr == NULL)
3399                         xlog_panic("xlog_verify_iclog: invalid ptr");
3400                 icptr = icptr->ic_next;
3401         }
3402         if (icptr != log->l_iclog)
3403                 xlog_panic("xlog_verify_iclog: corrupt iclog ring");
3404         spin_unlock(&log->l_icloglock);
3405
3406         /* check log magic numbers */
3407         if (be32_to_cpu(iclog->ic_header.h_magicno) != XLOG_HEADER_MAGIC_NUM)
3408                 xlog_panic("xlog_verify_iclog: invalid magic num");
3409
3410         ptr = (xfs_caddr_t) &iclog->ic_header;
3411         for (ptr += BBSIZE; ptr < ((xfs_caddr_t)&iclog->ic_header) + count;
3412              ptr += BBSIZE) {
3413                 if (be32_to_cpu(*(__be32 *)ptr) == XLOG_HEADER_MAGIC_NUM)
3414                         xlog_panic("xlog_verify_iclog: unexpected magic num");
3415         }
3416
3417         /* check fields */
3418         len = be32_to_cpu(iclog->ic_header.h_num_logops);
3419         ptr = iclog->ic_datap;
3420         base_ptr = ptr;
3421         ophead = (xlog_op_header_t *)ptr;
3422         xhdr = (xlog_in_core_2_t *)&iclog->ic_header;
3423         for (i = 0; i < len; i++) {
3424                 ophead = (xlog_op_header_t *)ptr;
3425
3426                 /* clientid is only 1 byte */
3427                 field_offset = (__psint_t)
3428                                ((xfs_caddr_t)&(ophead->oh_clientid) - base_ptr);
3429                 if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3430                         clientid = ophead->oh_clientid;
3431                 } else {
3432                         idx = BTOBBT((xfs_caddr_t)&(ophead->oh_clientid) - iclog->ic_datap);
3433                         if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3434                                 j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3435                                 k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3436                                 clientid = xlog_get_client_id(
3437                                         xhdr[j].hic_xheader.xh_cycle_data[k]);
3438                         } else {
3439                                 clientid = xlog_get_client_id(
3440                                         iclog->ic_header.h_cycle_data[idx]);
3441                         }
3442                 }
3443                 if (clientid != XFS_TRANSACTION && clientid != XFS_LOG)
3444                         cmn_err(CE_WARN, "xlog_verify_iclog: "
3445                                 "invalid clientid %d op 0x%p offset 0x%lx",
3446                                 clientid, ophead, (unsigned long)field_offset);
3447
3448                 /* check length */
3449                 field_offset = (__psint_t)
3450                                ((xfs_caddr_t)&(ophead->oh_len) - base_ptr);
3451                 if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3452                         op_len = be32_to_cpu(ophead->oh_len);
3453                 } else {
3454                         idx = BTOBBT((__psint_t)&ophead->oh_len -
3455                                     (__psint_t)iclog->ic_datap);
3456                         if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3457                                 j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3458                                 k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3459                                 op_len = be32_to_cpu(xhdr[j].hic_xheader.xh_cycle_data[k]);
3460                         } else {
3461                                 op_len = be32_to_cpu(iclog->ic_header.h_cycle_data[idx]);
3462                         }
3463                 }
3464                 ptr += sizeof(xlog_op_header_t) + op_len;
3465         }
3466 }       /* xlog_verify_iclog */
3467 #endif
3468
3469 /*
3470  * Mark all iclogs IOERROR. l_icloglock is held by the caller.
3471  */
3472 STATIC int
3473 xlog_state_ioerror(
3474         xlog_t  *log)
3475 {
3476         xlog_in_core_t  *iclog, *ic;
3477
3478         iclog = log->l_iclog;
3479         if (! (iclog->ic_state & XLOG_STATE_IOERROR)) {
3480                 /*
3481                  * Mark all the incore logs IOERROR.
3482                  * From now on, no log flushes will result.
3483                  */
3484                 ic = iclog;
3485                 do {
3486                         ic->ic_state = XLOG_STATE_IOERROR;
3487                         ic = ic->ic_next;
3488                 } while (ic != iclog);
3489                 return 0;
3490         }
3491         /*
3492          * Return non-zero, if state transition has already happened.
3493          */
3494         return 1;
3495 }
3496
3497 /*
3498  * This is called from xfs_force_shutdown, when we're forcibly
3499  * shutting down the filesystem, typically because of an IO error.
3500  * Our main objectives here are to make sure that:
3501  *      a. the filesystem gets marked 'SHUTDOWN' for all interested
3502  *         parties to find out, 'atomically'.
3503  *      b. those who're sleeping on log reservations, pinned objects and
3504  *          other resources get woken up, and be told the bad news.
3505  *      c. nothing new gets queued up after (a) and (b) are done.
3506  *      d. if !logerror, flush the iclogs to disk, then seal them off
3507  *         for business.
3508  */
3509 int
3510 xfs_log_force_umount(
3511         struct xfs_mount        *mp,
3512         int                     logerror)
3513 {
3514         xlog_ticket_t   *tic;
3515         xlog_t          *log;
3516         int             retval;
3517         int             dummy;
3518
3519         log = mp->m_log;
3520
3521         /*
3522          * If this happens during log recovery, don't worry about
3523          * locking; the log isn't open for business yet.
3524          */
3525         if (!log ||
3526             log->l_flags & XLOG_ACTIVE_RECOVERY) {
3527                 mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3528                 XFS_BUF_DONE(mp->m_sb_bp);
3529                 return 0;
3530         }
3531
3532         /*
3533          * Somebody could've already done the hard work for us.
3534          * No need to get locks for this.
3535          */
3536         if (logerror && log->l_iclog->ic_state & XLOG_STATE_IOERROR) {
3537                 ASSERT(XLOG_FORCED_SHUTDOWN(log));
3538                 return 1;
3539         }
3540         retval = 0;
3541         /*
3542          * We must hold both the GRANT lock and the LOG lock,
3543          * before we mark the filesystem SHUTDOWN and wake
3544          * everybody up to tell the bad news.
3545          */
3546         spin_lock(&log->l_icloglock);
3547         spin_lock(&log->l_grant_lock);
3548         mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3549         XFS_BUF_DONE(mp->m_sb_bp);
3550         /*
3551          * This flag is sort of redundant because of the mount flag, but
3552          * it's good to maintain the separation between the log and the rest
3553          * of XFS.
3554          */
3555         log->l_flags |= XLOG_IO_ERROR;
3556
3557         /*
3558          * If we hit a log error, we want to mark all the iclogs IOERROR
3559          * while we're still holding the loglock.
3560          */
3561         if (logerror)
3562                 retval = xlog_state_ioerror(log);
3563         spin_unlock(&log->l_icloglock);
3564
3565         /*
3566          * We don't want anybody waiting for log reservations
3567          * after this. That means we have to wake up everybody
3568          * queued up on reserve_headq as well as write_headq.
3569          * In addition, we make sure in xlog_{re}grant_log_space
3570          * that we don't enqueue anything once the SHUTDOWN flag
3571          * is set, and this action is protected by the GRANTLOCK.
3572          */
3573         if ((tic = log->l_reserve_headq)) {
3574                 do {
3575                         sv_signal(&tic->t_wait);
3576                         tic = tic->t_next;
3577                 } while (tic != log->l_reserve_headq);
3578         }
3579
3580         if ((tic = log->l_write_headq)) {
3581                 do {
3582                         sv_signal(&tic->t_wait);
3583                         tic = tic->t_next;
3584                 } while (tic != log->l_write_headq);
3585         }
3586         spin_unlock(&log->l_grant_lock);
3587
3588         if (! (log->l_iclog->ic_state & XLOG_STATE_IOERROR)) {
3589                 ASSERT(!logerror);
3590                 /*
3591                  * Force the incore logs to disk before shutting the
3592                  * log down completely.
3593                  */
3594                 xlog_state_sync_all(log, XFS_LOG_FORCE|XFS_LOG_SYNC, &dummy);
3595                 spin_lock(&log->l_icloglock);
3596                 retval = xlog_state_ioerror(log);
3597                 spin_unlock(&log->l_icloglock);
3598         }
3599         /*
3600          * Wake up everybody waiting on xfs_log_force.
3601          * Callback all log item committed functions as if the
3602          * log writes were completed.
3603          */
3604         xlog_state_do_callback(log, XFS_LI_ABORTED, NULL);
3605
3606 #ifdef XFSERRORDEBUG
3607         {
3608                 xlog_in_core_t  *iclog;
3609
3610                 spin_lock(&log->l_icloglock);
3611                 iclog = log->l_iclog;
3612                 do {
3613                         ASSERT(iclog->ic_callback == 0);
3614                         iclog = iclog->ic_next;
3615                 } while (iclog != log->l_iclog);
3616                 spin_unlock(&log->l_icloglock);
3617         }
3618 #endif
3619         /* return non-zero if log IOERROR transition had already happened */
3620         return retval;
3621 }
3622
3623 STATIC int
3624 xlog_iclogs_empty(xlog_t *log)
3625 {
3626         xlog_in_core_t  *iclog;
3627
3628         iclog = log->l_iclog;
3629         do {
3630                 /* endianness does not matter here, zero is zero in
3631                  * any language.
3632                  */
3633                 if (iclog->ic_header.h_num_logops)
3634                         return 0;
3635                 iclog = iclog->ic_next;
3636         } while (iclog != log->l_iclog);
3637         return 1;
3638 }