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