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