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