Whamcloud - gitweb
LU-5297 osp: process unsuccessful osp sync records properly
[fs/lustre-release.git] / lustre / osp / osp_sync.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osp/osp_sync.c
37  *
38  * Lustre OST Proxy Device
39  *
40  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
41  * Author: Mikhail Pershin <mike.pershin@intel.com>
42  */
43
44 #define DEBUG_SUBSYSTEM S_MDS
45
46 #include <linux/kthread.h>
47 #include <lustre_log.h>
48 #include <lustre_update.h>
49 #include "osp_internal.h"
50
51 static int osp_sync_id_traction_init(struct osp_device *d);
52 static void osp_sync_id_traction_fini(struct osp_device *d);
53 static __u32 osp_sync_id_get(struct osp_device *d, __u32 id);
54 static void osp_sync_remove_from_tracker(struct osp_device *d);
55
56 /*
57  * this is a components of OSP implementing synchronization between MDS and OST
58  * it llogs all interesting changes (currently it's uig/gid change and object
59  * destroy) atomically, then makes sure changes hit OST storage
60  *
61  * we have 4 queues of work:
62  *
63  * the first queue is llog itself, once read a change is stored in 2nd queue
64  * in form of RPC (but RPC isn't fired yet).
65  *
66  * the second queue (opd_syn_waiting_for_commit) holds changes awaiting local
67  * commit. once change is committed locally it migrates onto 3rd queue.
68  *
69  * the third queue (opd_syn_committed_here) holds changes committed locally,
70  * but not sent to OST (as the pipe can be full). once pipe becomes non-full
71  * we take a change from the queue and fire corresponded RPC.
72  *
73  * once RPC is reported committed by OST (using regular last_committed mech.)
74  * the change jumps into 4th queue (opd_syn_committed_there), now we can
75  * cancel corresponded llog record and release RPC
76  *
77  * opd_syn_changes is a number of unread llog records (to be processed).
78  * notice this number doesn't include llog records from previous boots.
79  * with OSP_SYN_THRESHOLD we try to batch processing a bit (TO BE IMPLEMENTED)
80  *
81  * opd_syn_rpc_in_progress is a number of requests in 2-4 queues.
82  * we control this with OSP_MAX_IN_PROGRESS so that OSP don't consume
83  * too much memory -- how to deal with 1000th OSTs ? batching could help?
84  *
85  * opd_syn_rpc_in_flight is a number of RPC in flight.
86  * we control this with OSP_MAX_IN_FLIGHT
87  */
88
89 /* XXX: do math to learn reasonable threshold
90  * should it be ~ number of changes fitting bulk? */
91
92 #define OSP_SYN_THRESHOLD       10
93 #define OSP_MAX_IN_FLIGHT       8
94 #define OSP_MAX_IN_PROGRESS     4096
95
96 #define OSP_JOB_MAGIC           0x26112005
97
98 struct osp_job_req_args {
99         /** bytes reserved for ptlrpc_replay_req() */
100         struct ptlrpc_replay_async_args jra_raa;
101         struct list_head                jra_link;
102         __u32                           jra_magic;
103 };
104
105 static inline int osp_sync_running(struct osp_device *d)
106 {
107         return !!(d->opd_syn_thread.t_flags & SVC_RUNNING);
108 }
109
110 /**
111  * Check status: whether OSP thread has stopped
112  *
113  * \param[in] d         OSP device
114  *
115  * \retval 0            still running
116  * \retval 1            stopped
117  */
118 static inline int osp_sync_stopped(struct osp_device *d)
119 {
120         return !!(d->opd_syn_thread.t_flags & SVC_STOPPED);
121 }
122
123 /*
124  ** Check for new changes to sync
125  *
126  * \param[in] d         OSP device
127  *
128  * \retval 1            there are changes
129  * \retval 0            there are no changes
130  */
131 static inline int osp_sync_has_new_job(struct osp_device *d)
132 {
133         return ((d->opd_syn_last_processed_id < d->opd_syn_last_used_id) &&
134                 (d->opd_syn_last_processed_id < d->opd_syn_last_committed_id))
135                 || (d->opd_syn_prev_done == 0);
136 }
137
138 static inline int osp_sync_low_in_progress(struct osp_device *d)
139 {
140         return d->opd_syn_rpc_in_progress < d->opd_syn_max_rpc_in_progress;
141 }
142
143 /**
144  * Check for room in the network pipe to OST
145  *
146  * \param[in] d         OSP device
147  *
148  * \retval 1            there is room
149  * \retval 0            no room, the pipe is full
150  */
151 static inline int osp_sync_low_in_flight(struct osp_device *d)
152 {
153         return d->opd_syn_rpc_in_flight < d->opd_syn_max_rpc_in_flight;
154 }
155
156 /**
157  * Wake up check for the main sync thread
158  *
159  * \param[in] d         OSP device
160  *
161  * \retval 1            time to wake up
162  * \retval 0            no need to wake up
163  */
164 static inline int osp_sync_has_work(struct osp_device *d)
165 {
166         /* has new/old changes and low in-progress? */
167         if (osp_sync_has_new_job(d) && osp_sync_low_in_progress(d) &&
168             osp_sync_low_in_flight(d) && d->opd_imp_connected)
169                 return 1;
170
171         /* has remotely committed? */
172         if (!list_empty(&d->opd_syn_committed_there))
173                 return 1;
174
175         return 0;
176 }
177
178 #define osp_sync_check_for_work(d)                      \
179 {                                                       \
180         if (osp_sync_has_work(d)) {                     \
181                 wake_up(&d->opd_syn_waitq);    \
182         }                                               \
183 }
184
185 void __osp_sync_check_for_work(struct osp_device *d)
186 {
187         osp_sync_check_for_work(d);
188 }
189
190 /**
191  * Check and return ready-for-new status.
192  *
193  * The thread processing llog record uses this function to check whether
194  * it's time to take another record and process it. The number of conditions
195  * must be met: the connection should be ready, RPCs in flight not exceeding
196  * the limit, the record is committed locally, etc (see the lines below).
197  *
198  * \param[in] d         OSP device
199  * \param[in] rec       next llog record to process
200  *
201  * \retval 0            not ready
202  * \retval 1            ready
203  */
204 static inline int osp_sync_can_process_new(struct osp_device *d,
205                                            struct llog_rec_hdr *rec)
206 {
207         LASSERT(d);
208
209         if (unlikely(atomic_read(&d->opd_syn_barrier) > 0))
210                 return 0;
211         if (!osp_sync_low_in_progress(d))
212                 return 0;
213         if (!osp_sync_low_in_flight(d))
214                 return 0;
215         if (!d->opd_imp_connected)
216                 return 0;
217         if (d->opd_syn_prev_done == 0)
218                 return 1;
219         if (d->opd_syn_changes == 0)
220                 return 0;
221         if (rec == NULL || rec->lrh_id <= d->opd_syn_last_committed_id)
222                 return 1;
223         return 0;
224 }
225
226 /**
227  * Declare intention to add a new change.
228  *
229  * With regard to OSD API, we have to declare any changes ahead. In this
230  * case we declare an intention to add a llog record representing the
231  * change on the local storage.
232  *
233  * \param[in] env       LU environment provided by the caller
234  * \param[in] o         OSP object
235  * \param[in] type      type of change: MDS_UNLINK64_REC or MDS_SETATTR64_REC
236  * \param[in] th        transaction handle (local)
237  *
238  * \retval 0            on success
239  * \retval negative     negated errno on error
240  */
241 int osp_sync_declare_add(const struct lu_env *env, struct osp_object *o,
242                          llog_op_type type, struct thandle *th)
243 {
244         struct osp_thread_info  *osi = osp_env_info(env);
245         struct osp_device       *d = lu2osp_dev(o->opo_obj.do_lu.lo_dev);
246         struct llog_ctxt        *ctxt;
247         struct thandle          *storage_th;
248         int                      rc;
249
250         ENTRY;
251
252         /* it's a layering violation, to access internals of th,
253          * but we can do this as a sanity check, for a while */
254         LASSERT(th->th_top != NULL);
255         storage_th = thandle_get_sub_by_dt(env, th->th_top, d->opd_storage);
256         if (IS_ERR(storage_th))
257                 RETURN(PTR_ERR(storage_th));
258
259         switch (type) {
260         case MDS_UNLINK64_REC:
261                 osi->osi_hdr.lrh_len = sizeof(struct llog_unlink64_rec);
262                 break;
263         case MDS_SETATTR64_REC:
264                 osi->osi_hdr.lrh_len = sizeof(struct llog_setattr64_rec);
265                 break;
266         default:
267                 LBUG();
268         }
269
270         /* we want ->dt_trans_start() to allocate per-thandle structure */
271         storage_th->th_tags |= LCT_OSP_THREAD;
272
273         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
274         LASSERT(ctxt);
275
276         rc = llog_declare_add(env, ctxt->loc_handle, &osi->osi_hdr,
277                               storage_th);
278         llog_ctxt_put(ctxt);
279
280         RETURN(rc);
281 }
282
283 /**
284  * Generate a llog record for a given change.
285  *
286  * Generates a llog record for the change passed. The change can be of two
287  * types: unlink and setattr. The record gets an ID which later will be
288  * used to track commit status of the change. For unlink changes, the caller
289  * can supply a starting FID and the count of the objects to destroy. For
290  * setattr the caller should apply attributes to apply.
291  *
292  *
293  * \param[in] env       LU environment provided by the caller
294  * \param[in] d         OSP device
295  * \param[in] fid       fid of the object the change should be applied to
296  * \param[in] type      type of change: MDS_UNLINK64_REC or MDS_SETATTR64_REC
297  * \param[in] count     count of objects to destroy
298  * \param[in] th        transaction handle (local)
299  * \param[in] attr      attributes for setattr
300  *
301  * \retval 0            on success
302  * \retval negative     negated errno on error
303  */
304 static int osp_sync_add_rec(const struct lu_env *env, struct osp_device *d,
305                             const struct lu_fid *fid, llog_op_type type,
306                             int count, struct thandle *th,
307                             const struct lu_attr *attr)
308 {
309         struct osp_thread_info  *osi = osp_env_info(env);
310         struct llog_ctxt        *ctxt;
311         struct osp_txn_info     *txn;
312         struct thandle          *storage_th;
313         int                      rc;
314
315         ENTRY;
316
317         /* it's a layering violation, to access internals of th,
318          * but we can do this as a sanity check, for a while */
319         LASSERT(th->th_top != NULL);
320         storage_th = thandle_get_sub_by_dt(env, th->th_top, d->opd_storage);
321         if (IS_ERR(storage_th))
322                 RETURN(PTR_ERR(storage_th));
323
324         switch (type) {
325         case MDS_UNLINK64_REC:
326                 osi->osi_hdr.lrh_len = sizeof(osi->osi_unlink);
327                 osi->osi_hdr.lrh_type = MDS_UNLINK64_REC;
328                 osi->osi_unlink.lur_fid  = *fid;
329                 osi->osi_unlink.lur_count = count;
330                 break;
331         case MDS_SETATTR64_REC:
332                 rc = fid_to_ostid(fid, &osi->osi_oi);
333                 LASSERT(rc == 0);
334                 osi->osi_hdr.lrh_len = sizeof(osi->osi_setattr);
335                 osi->osi_hdr.lrh_type = MDS_SETATTR64_REC;
336                 osi->osi_setattr.lsr_oi  = osi->osi_oi;
337                 LASSERT(attr);
338                 osi->osi_setattr.lsr_uid = attr->la_uid;
339                 osi->osi_setattr.lsr_gid = attr->la_gid;
340                 osi->osi_setattr.lsr_valid =
341                         ((attr->la_valid & LA_UID) ? OBD_MD_FLUID : 0) |
342                         ((attr->la_valid & LA_GID) ? OBD_MD_FLGID : 0);
343                 break;
344         default:
345                 LBUG();
346         }
347
348         txn = osp_txn_info(&storage_th->th_ctx);
349         LASSERT(txn);
350
351         txn->oti_current_id = osp_sync_id_get(d, txn->oti_current_id);
352         osi->osi_hdr.lrh_id = txn->oti_current_id;
353
354         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
355         if (ctxt == NULL)
356                 RETURN(-ENOMEM);
357
358         rc = llog_add(env, ctxt->loc_handle, &osi->osi_hdr, &osi->osi_cookie,
359                       storage_th);
360         llog_ctxt_put(ctxt);
361
362         if (likely(rc >= 0)) {
363                 CDEBUG(D_OTHER, "%s: new record "DOSTID":%lu/%lu: %d\n",
364                        d->opd_obd->obd_name,
365                        POSTID(&osi->osi_cookie.lgc_lgl.lgl_oi),
366                        (unsigned long)osi->osi_cookie.lgc_lgl.lgl_ogen,
367                        (unsigned long)osi->osi_cookie.lgc_index, rc);
368                 spin_lock(&d->opd_syn_lock);
369                 d->opd_syn_changes++;
370                 spin_unlock(&d->opd_syn_lock);
371         }
372         /* return 0 always here, error case just cause no llog record */
373         RETURN(0);
374 }
375
376 int osp_sync_add(const struct lu_env *env, struct osp_object *o,
377                  llog_op_type type, struct thandle *th,
378                  const struct lu_attr *attr)
379 {
380         return osp_sync_add_rec(env, lu2osp_dev(o->opo_obj.do_lu.lo_dev),
381                                 lu_object_fid(&o->opo_obj.do_lu), type, 1,
382                                 th, attr);
383 }
384
385 int osp_sync_gap(const struct lu_env *env, struct osp_device *d,
386                         struct lu_fid *fid, int lost, struct thandle *th)
387 {
388         return osp_sync_add_rec(env, d, fid, MDS_UNLINK64_REC, lost, th, NULL);
389 }
390
391 /*
392  * it's quite obvious we can't maintain all the structures in the memory:
393  * while OST is down, MDS can be processing thousands and thousands of unlinks
394  * filling persistent llogs and in-core respresentation
395  *
396  * this doesn't scale at all. so we need basically the following:
397  * a) destroy/setattr append llog records
398  * b) once llog has grown to X records, we process first Y committed records
399  *
400  *  once record R is found via llog_process(), it becomes committed after any
401  *  subsequent commit callback (at the most)
402  */
403
404 /**
405  * ptlrpc commit callback.
406  *
407  * The callback is called by PTLRPC when a RPC is reported committed by the
408  * target (OST). We register the callback for the every RPC applying a change
409  * from the llog. This way we know then the llog records can be cancelled.
410  * Notice the callback can be called when OSP is finishing. We can detect this
411  * checking that actual transno in the request is less or equal of known
412  * committed transno (see osp_sync_process_committed() for the details).
413  * XXX: this is pretty expensive and can be improved later using batching.
414  *
415  * \param[in] req       request
416  */
417 static void osp_sync_request_commit_cb(struct ptlrpc_request *req)
418 {
419         struct osp_device *d = req->rq_cb_data;
420         struct osp_job_req_args *jra;
421
422         CDEBUG(D_HA, "commit req %p, transno "LPU64"\n", req, req->rq_transno);
423
424         if (unlikely(req->rq_transno == 0))
425                 return;
426
427         /* do not do any opd_dyn_rpc_* accounting here
428          * it's done in osp_sync_interpret sooner or later */
429         LASSERT(d);
430
431         jra = ptlrpc_req_async_args(req);
432         LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
433         LASSERT(list_empty(&jra->jra_link));
434
435         ptlrpc_request_addref(req);
436
437         spin_lock(&d->opd_syn_lock);
438         list_add(&jra->jra_link, &d->opd_syn_committed_there);
439         spin_unlock(&d->opd_syn_lock);
440
441         /* XXX: some batching wouldn't hurt */
442         wake_up(&d->opd_syn_waitq);
443 }
444
445 /**
446  * RPC interpretation callback.
447  *
448  * The callback is called by ptlrpc when RPC is replied. Now we have to decide
449  * whether we should:
450  *  - put request on a special list to wait until it's committed by the target,
451  *    if the request is successful
452  *  - schedule llog record cancel if no target object is found
453  *  - try later (essentially after reboot) in case of unexpected error
454  *
455  * \param[in] env       LU environment provided by the caller
456  * \param[in] req       request replied
457  * \param[in] aa        callback data
458  * \param[in] rc        result of RPC
459  *
460  * \retval 0            always
461  */
462 static int osp_sync_interpret(const struct lu_env *env,
463                               struct ptlrpc_request *req, void *aa, int rc)
464 {
465         struct osp_device *d = req->rq_cb_data;
466         struct osp_job_req_args *jra = aa;
467
468         if (jra->jra_magic != OSP_JOB_MAGIC) {
469                 DEBUG_REQ(D_ERROR, req, "bad magic %u\n", jra->jra_magic);
470                 LBUG();
471         }
472         LASSERT(d);
473
474         CDEBUG(D_HA, "reply req %p/%d, rc %d, transno %u\n", req,
475                atomic_read(&req->rq_refcount),
476                rc, (unsigned) req->rq_transno);
477         LASSERT(rc || req->rq_transno);
478
479         if (rc == -ENOENT) {
480                 /*
481                  * we tried to destroy object or update attributes,
482                  * but object doesn't exist anymore - cancell llog record
483                  */
484                 LASSERT(req->rq_transno == 0);
485                 LASSERT(list_empty(&jra->jra_link));
486
487                 ptlrpc_request_addref(req);
488
489                 spin_lock(&d->opd_syn_lock);
490                 list_add(&jra->jra_link, &d->opd_syn_committed_there);
491                 spin_unlock(&d->opd_syn_lock);
492
493                 wake_up(&d->opd_syn_waitq);
494         } else if (rc) {
495                 struct obd_import *imp = req->rq_import;
496                 /*
497                  * error happened, we'll try to repeat on next boot ?
498                  */
499                 LASSERTF(req->rq_transno == 0 ||
500                          req->rq_import_generation < imp->imp_generation,
501                          "transno "LPU64", rc %d, gen: req %d, imp %d\n",
502                          req->rq_transno, rc, req->rq_import_generation,
503                          imp->imp_generation);
504                 if (req->rq_transno == 0) {
505                         /* this is the last time we see the request
506                          * if transno is not zero, then commit cb
507                          * will be called at some point */
508                         LASSERT(d->opd_syn_rpc_in_progress > 0);
509                         spin_lock(&d->opd_syn_lock);
510                         d->opd_syn_rpc_in_progress--;
511                         spin_unlock(&d->opd_syn_lock);
512                 }
513
514                 wake_up(&d->opd_syn_waitq);
515         } else if (d->opd_pre != NULL &&
516                    unlikely(d->opd_pre_status == -ENOSPC)) {
517                 /*
518                  * if current status is -ENOSPC (lack of free space on OST)
519                  * then we should poll OST immediately once object destroy
520                  * is replied
521                  */
522                 osp_statfs_need_now(d);
523         }
524
525         LASSERT(d->opd_syn_rpc_in_flight > 0);
526         spin_lock(&d->opd_syn_lock);
527         d->opd_syn_rpc_in_flight--;
528         spin_unlock(&d->opd_syn_lock);
529         if (unlikely(atomic_read(&d->opd_syn_barrier) > 0))
530                 wake_up(&d->opd_syn_barrier_waitq);
531         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
532                d->opd_obd->obd_name, d->opd_syn_rpc_in_flight,
533                d->opd_syn_rpc_in_progress);
534
535         osp_sync_check_for_work(d);
536
537         return 0;
538 }
539
540 /*
541  ** Add request to ptlrpc queue.
542  *
543  * This is just a tiny helper function to put the request on the sending list
544  *
545  * \param[in] d         OSP device
546  * \param[in] req       request
547  */
548 static void osp_sync_send_new_rpc(struct osp_device *d,
549                                   struct ptlrpc_request *req)
550 {
551         struct osp_job_req_args *jra;
552
553         LASSERT(d->opd_syn_rpc_in_flight <= d->opd_syn_max_rpc_in_flight);
554
555         jra = ptlrpc_req_async_args(req);
556         jra->jra_magic = OSP_JOB_MAGIC;
557         INIT_LIST_HEAD(&jra->jra_link);
558
559         ptlrpcd_add_req(req);
560 }
561
562
563 /**
564  * Allocate and prepare RPC for a new change.
565  *
566  * The function allocates and initializes an RPC which will be sent soon to
567  * apply the change to the target OST. The request is initialized from the
568  * llog record passed. Notice only the fields common to all type of changes
569  * are initialized.
570  *
571  * \param[in] d         OSP device
572  * \param[in] llh       llog handle where the record is stored
573  * \param[in] h         llog record
574  * \param[in] op        type of the change
575  * \param[in] format    request format to be used
576  *
577  * \retval pointer              new request on success
578  * \retval ERR_PTR(errno)       on error
579  */
580 static struct ptlrpc_request *osp_sync_new_job(struct osp_device *d,
581                                                struct llog_handle *llh,
582                                                struct llog_rec_hdr *h,
583                                                ost_cmd_t op,
584                                                const struct req_format *format)
585 {
586         struct ptlrpc_request   *req;
587         struct ost_body         *body;
588         struct obd_import       *imp;
589         int                      rc;
590
591         /* Prepare the request */
592         imp = d->opd_obd->u.cli.cl_import;
593         LASSERT(imp);
594
595         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_CHECK_ENOMEM))
596                 RETURN(ERR_PTR(-ENOMEM));
597
598         req = ptlrpc_request_alloc(imp, format);
599         if (req == NULL)
600                 RETURN(ERR_PTR(-ENOMEM));
601
602         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, op);
603         if (rc) {
604                 ptlrpc_req_finished(req);
605                 return ERR_PTR(rc);
606         }
607
608         /*
609          * this is a trick: to save on memory allocations we put cookie
610          * into the request, but don't set corresponded flag in o_valid
611          * so that OST doesn't interpret this cookie. once the request
612          * is committed on OST we take cookie from the request and cancel
613          */
614         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
615         LASSERT(body);
616         body->oa.o_lcookie.lgc_lgl = llh->lgh_id;
617         body->oa.o_lcookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
618         body->oa.o_lcookie.lgc_index = h->lrh_index;
619
620         req->rq_interpret_reply = osp_sync_interpret;
621         req->rq_commit_cb = osp_sync_request_commit_cb;
622         req->rq_cb_data = d;
623
624         ptlrpc_request_set_replen(req);
625
626         return req;
627 }
628
629 /**
630  * Generate a request for setattr change.
631  *
632  * The function prepares a new RPC, initializes it with setattr specific
633  * bits and send the RPC.
634  *
635  * \param[in] d         OSP device
636  * \param[in] llh       llog handle where the record is stored
637  * \param[in] h         llog record
638  *
639  * \retval 0            on success
640  * \retval 1            on invalid record
641  * \retval negative     negated errno on error
642  */
643 static int osp_sync_new_setattr_job(struct osp_device *d,
644                                     struct llog_handle *llh,
645                                     struct llog_rec_hdr *h)
646 {
647         struct llog_setattr64_rec       *rec = (struct llog_setattr64_rec *)h;
648         struct ptlrpc_request           *req;
649         struct ost_body                 *body;
650
651         ENTRY;
652         LASSERT(h->lrh_type == MDS_SETATTR64_REC);
653
654         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_CHECK_INVALID_REC))
655                 RETURN(1);
656         /* lsr_valid can only be 0 or have OBD_MD_{FLUID,FLGID} set,
657          * so no bits other than these should be set. */
658         if ((rec->lsr_valid & ~(OBD_MD_FLUID | OBD_MD_FLGID)) != 0) {
659                 CERROR("%s: invalid setattr record, lsr_valid:"LPU64"\n",
660                        d->opd_obd->obd_name, rec->lsr_valid);
661                 /* return 1 on invalid record */
662                 RETURN(1);
663         }
664
665         req = osp_sync_new_job(d, llh, h, OST_SETATTR, &RQF_OST_SETATTR);
666         if (IS_ERR(req))
667                 RETURN(PTR_ERR(req));
668
669         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
670         LASSERT(body);
671         body->oa.o_oi = rec->lsr_oi;
672         body->oa.o_uid = rec->lsr_uid;
673         body->oa.o_gid = rec->lsr_gid;
674         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
675         /* old setattr record (prior 2.6.0) doesn't have 'valid' stored,
676          * we assume that both UID and GID are valid in that case. */
677         if (rec->lsr_valid == 0)
678                 body->oa.o_valid |= (OBD_MD_FLUID | OBD_MD_FLGID);
679         else
680                 body->oa.o_valid |= rec->lsr_valid;
681
682         osp_sync_send_new_rpc(d, req);
683         RETURN(0);
684 }
685
686 /**
687  * Generate a request for unlink change.
688  *
689  * The function prepares a new RPC, initializes it with unlink(destroy)
690  * specific bits and sends the RPC. The function is used to handle
691  * llog_unlink_rec which were used in the older versions of Lustre.
692  * Current version uses llog_unlink_rec64.
693  *
694  * \param[in] d         OSP device
695  * \param[in] llh       llog handle where the record is stored
696  * \param[in] h         llog record
697  *
698  * \retval 0            on success
699  * \retval negative     negated errno on error
700  */
701 static int osp_sync_new_unlink_job(struct osp_device *d,
702                                    struct llog_handle *llh,
703                                    struct llog_rec_hdr *h)
704 {
705         struct llog_unlink_rec  *rec = (struct llog_unlink_rec *)h;
706         struct ptlrpc_request   *req;
707         struct ost_body         *body;
708
709         ENTRY;
710         LASSERT(h->lrh_type == MDS_UNLINK_REC);
711
712         req = osp_sync_new_job(d, llh, h, OST_DESTROY, &RQF_OST_DESTROY);
713         if (IS_ERR(req))
714                 RETURN(PTR_ERR(req));
715
716         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
717         LASSERT(body);
718         ostid_set_seq(&body->oa.o_oi, rec->lur_oseq);
719         ostid_set_id(&body->oa.o_oi, rec->lur_oid);
720         body->oa.o_misc = rec->lur_count;
721         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
722         if (rec->lur_count)
723                 body->oa.o_valid |= OBD_MD_FLOBJCOUNT;
724
725         osp_sync_send_new_rpc(d, req);
726         RETURN(0);
727 }
728
729 /**
730  * Generate a request for unlink change.
731  *
732  * The function prepares a new RPC, initializes it with unlink(destroy)
733  * specific bits and sends the RPC. Depending on the target (MDT or OST)
734  * two different protocols are used. For MDT we use OUT (basically OSD API
735  * updates transferred via a network). For OST we still use the old
736  * protocol (OBD?), originally for compatibility. Later we can start to
737  * use OUT for OST as well, this will allow batching and better code
738  * unification.
739  *
740  * \param[in] d         OSP device
741  * \param[in] llh       llog handle where the record is stored
742  * \param[in] h         llog record
743  *
744  * \retval 0            on success
745  * \retval negative     negated errno on error
746  */
747 static int osp_sync_new_unlink64_job(struct osp_device *d,
748                                      struct llog_handle *llh,
749                                      struct llog_rec_hdr *h)
750 {
751         struct llog_unlink64_rec        *rec = (struct llog_unlink64_rec *)h;
752         struct ptlrpc_request           *req = NULL;
753         struct ost_body                 *body;
754         int                              rc;
755
756         ENTRY;
757         LASSERT(h->lrh_type == MDS_UNLINK64_REC);
758         req = osp_sync_new_job(d, llh, h, OST_DESTROY,
759                                &RQF_OST_DESTROY);
760         if (IS_ERR(req))
761                 RETURN(PTR_ERR(req));
762
763         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
764         if (body == NULL)
765                 RETURN(-EFAULT);
766         rc = fid_to_ostid(&rec->lur_fid, &body->oa.o_oi);
767         if (rc < 0)
768                 RETURN(rc);
769         body->oa.o_misc = rec->lur_count;
770         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID |
771                            OBD_MD_FLOBJCOUNT;
772         osp_sync_send_new_rpc(d, req);
773         RETURN(0);
774 }
775
776 /**
777  * Process llog records.
778  *
779  * This function is called to process the llog records committed locally.
780  * In the recovery model used by OSP we can apply a change to a remote
781  * target once corresponding transaction (like posix unlink) is committed
782  * locally so can't revert.
783  * Depending on the llog record type, a given handler is called that is
784  * responsible for preparing and sending the RPC to apply the change.
785  * Special record type LLOG_GEN_REC marking a reboot is cancelled right away.
786  *
787  * \param[in] env       LU environment provided by the caller
788  * \param[in] d         OSP device
789  * \param[in] llh       llog handle where the record is stored
790  * \param[in] rec       llog record
791  */
792 static void osp_sync_process_record(const struct lu_env *env,
793                                     struct osp_device *d,
794                                     struct llog_handle *llh,
795                                     struct llog_rec_hdr *rec)
796 {
797         struct llog_handle      *cathandle = llh->u.phd.phd_cat_handle;
798         struct llog_cookie       cookie;
799         int                      rc = 0;
800
801         ENTRY;
802
803         cookie.lgc_lgl = llh->lgh_id;
804         cookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
805         cookie.lgc_index = rec->lrh_index;
806
807         if (unlikely(rec->lrh_type == LLOG_GEN_REC)) {
808                 struct llog_gen_rec *gen = (struct llog_gen_rec *)rec;
809
810                 /* we're waiting for the record generated by this instance */
811                 LASSERT(d->opd_syn_prev_done == 0);
812                 if (!memcmp(&d->opd_syn_generation, &gen->lgr_gen,
813                             sizeof(gen->lgr_gen))) {
814                         CDEBUG(D_HA, "processed all old entries\n");
815                         d->opd_syn_prev_done = 1;
816                 }
817
818                 /* cancel any generation record */
819                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
820
821                 RETURN_EXIT;
822         }
823
824         /*
825          * now we prepare and fill requests to OST, put them on the queue
826          * and fire after next commit callback
827          */
828
829         /* notice we increment counters before sending RPC, to be consistent
830          * in RPC interpret callback which may happen very quickly */
831         spin_lock(&d->opd_syn_lock);
832         d->opd_syn_rpc_in_flight++;
833         d->opd_syn_rpc_in_progress++;
834         spin_unlock(&d->opd_syn_lock);
835
836         switch (rec->lrh_type) {
837         /* case MDS_UNLINK_REC is kept for compatibility */
838         case MDS_UNLINK_REC:
839                 rc = osp_sync_new_unlink_job(d, llh, rec);
840                 break;
841         case MDS_UNLINK64_REC:
842                 rc = osp_sync_new_unlink64_job(d, llh, rec);
843                 break;
844         case MDS_SETATTR64_REC:
845                 rc = osp_sync_new_setattr_job(d, llh, rec);
846                 break;
847         default:
848                 CERROR("%s: unknown record type: %x\n", d->opd_obd->obd_name,
849                        rec->lrh_type);
850                 /* treat "unknown record type" as "invalid" */
851                 rc = 1;
852                 break;
853         }
854
855         spin_lock(&d->opd_syn_lock);
856
857         /* For all kinds of records, not matter successful or not,
858          * we should decrease changes and bump last_processed_id.
859          */
860         if (d->opd_syn_prev_done) {
861                 LASSERT(d->opd_syn_changes > 0);
862                 LASSERT(rec->lrh_id <= d->opd_syn_last_committed_id);
863                 /* NOTE: it's possible to meet same id if
864                  * OST stores few stripes of same file
865                  */
866                 if (rec->lrh_id > d->opd_syn_last_processed_id) {
867                         d->opd_syn_last_processed_id = rec->lrh_id;
868                         wake_up(&d->opd_syn_barrier_waitq);
869                 }
870                 d->opd_syn_changes--;
871         }
872         if (rc != 0) {
873                 d->opd_syn_rpc_in_flight--;
874                 d->opd_syn_rpc_in_progress--;
875         }
876         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
877                d->opd_obd->obd_name, d->opd_syn_rpc_in_flight,
878                d->opd_syn_rpc_in_progress);
879
880         spin_unlock(&d->opd_syn_lock);
881
882         /* Delete the invalid record */
883         if (rc == 1) {
884                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
885                 if (rc != 0)
886                         CERROR("%s: can't delete invalid record: "
887                                "fid = "DFID", rec_id = %u, rc = %d\n",
888                                d->opd_obd->obd_name,
889                                PFID(lu_object_fid(&cathandle->lgh_obj->do_lu)),
890                                rec->lrh_id, rc);
891         }
892
893         CDEBUG(D_HA, "found record %x, %d, idx %u, id %u\n",
894                rec->lrh_type, rec->lrh_len, rec->lrh_index, rec->lrh_id);
895
896         RETURN_EXIT;
897 }
898
899 /**
900  * Cancel llog records for the committed changes.
901  *
902  * The function walks through the list of the committed RPCs and cancels
903  * corresponding llog records. see osp_sync_request_commit_cb() for the
904  * details.
905  *
906  * \param[in] env       LU environment provided by the caller
907  * \param[in] d         OSP device
908  */
909 static void osp_sync_process_committed(const struct lu_env *env,
910                                        struct osp_device *d)
911 {
912         struct obd_device       *obd = d->opd_obd;
913         struct obd_import       *imp = obd->u.cli.cl_import;
914         struct ost_body         *body;
915         struct ptlrpc_request   *req;
916         struct llog_ctxt        *ctxt;
917         struct llog_handle      *llh;
918         struct list_head         list;
919         int                      rc, done = 0;
920
921         ENTRY;
922
923         if (list_empty(&d->opd_syn_committed_there))
924                 return;
925
926         /*
927          * if current status is -ENOSPC (lack of free space on OST)
928          * then we should poll OST immediately once object destroy
929          * is committed.
930          * notice: we do this upon commit as well because some backends
931          * (like DMU) do not release space right away.
932          */
933         if (d->opd_pre != NULL && unlikely(d->opd_pre_status == -ENOSPC))
934                 osp_statfs_need_now(d);
935
936         /*
937          * now cancel them all
938          * XXX: can we improve this using some batching?
939          *      with batch RPC that'll happen automatically?
940          * XXX: can we store ctxt in lod_device and save few cycles ?
941          */
942         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
943         LASSERT(ctxt);
944
945         llh = ctxt->loc_handle;
946         LASSERT(llh);
947
948         INIT_LIST_HEAD(&list);
949         spin_lock(&d->opd_syn_lock);
950         list_splice(&d->opd_syn_committed_there, &list);
951         INIT_LIST_HEAD(&d->opd_syn_committed_there);
952         spin_unlock(&d->opd_syn_lock);
953
954         while (!list_empty(&list)) {
955                 struct osp_job_req_args *jra;
956
957                 jra = list_entry(list.next, struct osp_job_req_args, jra_link);
958                 LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
959                 list_del_init(&jra->jra_link);
960
961                 req = container_of((void *)jra, struct ptlrpc_request,
962                                    rq_async_args);
963                 body = req_capsule_client_get(&req->rq_pill,
964                                               &RMF_OST_BODY);
965                 LASSERT(body);
966                 /* import can be closing, thus all commit cb's are
967                  * called we can check committness directly */
968                 if (req->rq_import_generation == imp->imp_generation) {
969                         rc = llog_cat_cancel_records(env, llh, 1,
970                                                      &body->oa.o_lcookie);
971                         if (rc)
972                                 CERROR("%s: can't cancel record: %d\n",
973                                        obd->obd_name, rc);
974                 } else {
975                         DEBUG_REQ(D_ERROR, req, "imp_committed = "LPU64,
976                                   imp->imp_peer_committed_transno);
977                 }
978                 ptlrpc_req_finished(req);
979                 done++;
980         }
981
982         llog_ctxt_put(ctxt);
983
984         LASSERT(d->opd_syn_rpc_in_progress >= done);
985         spin_lock(&d->opd_syn_lock);
986         d->opd_syn_rpc_in_progress -= done;
987         spin_unlock(&d->opd_syn_lock);
988         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
989                d->opd_obd->obd_name, d->opd_syn_rpc_in_flight,
990                d->opd_syn_rpc_in_progress);
991
992         osp_sync_check_for_work(d);
993
994         /* wake up the thread if requested to stop:
995          * it might be waiting for in-progress to complete */
996         if (unlikely(osp_sync_running(d) == 0))
997                 wake_up(&d->opd_syn_waitq);
998
999         EXIT;
1000 }
1001
1002 /**
1003  * The core of the syncing mechanism.
1004  *
1005  * This is a callback called by the llog processing function. Essentially it
1006  * suspends llog processing until there is a record to process (it's supposed
1007  * to be committed locally). The function handles RPCs committed by the target
1008  * and cancels corresponding llog records.
1009  *
1010  * \param[in] env       LU environment provided by the caller
1011  * \param[in] llh       llog handle we're processing
1012  * \param[in] rec       current llog record
1013  * \param[in] data      callback data containing a pointer to the device
1014  *
1015  * \retval 0                    to ask the caller (llog_process()) to continue
1016  * \retval LLOG_PROC_BREAK      to ask the caller to break
1017  */
1018 static int osp_sync_process_queues(const struct lu_env *env,
1019                                    struct llog_handle *llh,
1020                                    struct llog_rec_hdr *rec,
1021                                    void *data)
1022 {
1023         struct osp_device       *d = data;
1024
1025         do {
1026                 struct l_wait_info lwi = { 0 };
1027
1028                 if (!osp_sync_running(d)) {
1029                         CDEBUG(D_HA, "stop llog processing\n");
1030                         return LLOG_PROC_BREAK;
1031                 }
1032
1033                 /* process requests committed by OST */
1034                 osp_sync_process_committed(env, d);
1035
1036                 /* if we there are changes to be processed and we have
1037                  * resources for this ... do now */
1038                 if (osp_sync_can_process_new(d, rec)) {
1039                         if (llh == NULL) {
1040                                 /* ask llog for another record */
1041                                 CDEBUG(D_HA, "%lu changes, %u in progress,"
1042                                        " %u in flight\n",
1043                                        d->opd_syn_changes,
1044                                        d->opd_syn_rpc_in_progress,
1045                                        d->opd_syn_rpc_in_flight);
1046                                 return 0;
1047                         }
1048                         osp_sync_process_record(env, d, llh, rec);
1049                         llh = NULL;
1050                         rec = NULL;
1051                 }
1052
1053                 if (d->opd_syn_last_processed_id == d->opd_syn_last_used_id)
1054                         osp_sync_remove_from_tracker(d);
1055
1056                 l_wait_event(d->opd_syn_waitq,
1057                              !osp_sync_running(d) ||
1058                              osp_sync_can_process_new(d, rec) ||
1059                              !list_empty(&d->opd_syn_committed_there),
1060                              &lwi);
1061         } while (1);
1062 }
1063
1064 /**
1065  * OSP sync thread.
1066  *
1067  * This thread runs llog_cat_process() scanner calling our callback
1068  * to process llog records. in the callback we implement tricky
1069  * state machine as we don't want to start scanning of the llog again
1070  * and again, also we don't want to process too many records and send
1071  * too many RPCs a time. so, depending on current load (num of changes
1072  * being synced to OST) the callback can suspend awaiting for some
1073  * new conditions, like syncs completed.
1074  *
1075  * In order to process llog records left by previous boots and to allow
1076  * llog_process_thread() to find something (otherwise it'd just exit
1077  * immediately) we add a special GENERATATION record on each boot.
1078  *
1079  * \param[in] _arg      a pointer to thread's arguments
1080  *
1081  * \retval 0            on success
1082  * \retval negative     negated errno on error
1083  */
1084 static int osp_sync_thread(void *_arg)
1085 {
1086         struct osp_device       *d = _arg;
1087         struct ptlrpc_thread    *thread = &d->opd_syn_thread;
1088         struct l_wait_info       lwi = { 0 };
1089         struct llog_ctxt        *ctxt;
1090         struct obd_device       *obd = d->opd_obd;
1091         struct llog_handle      *llh;
1092         struct lu_env            env;
1093         int                      rc, count;
1094
1095         ENTRY;
1096
1097         rc = lu_env_init(&env, LCT_LOCAL);
1098         if (rc) {
1099                 CERROR("%s: can't initialize env: rc = %d\n",
1100                        obd->obd_name, rc);
1101                 RETURN(rc);
1102         }
1103
1104         spin_lock(&d->opd_syn_lock);
1105         thread->t_flags = SVC_RUNNING;
1106         spin_unlock(&d->opd_syn_lock);
1107         wake_up(&thread->t_ctl_waitq);
1108
1109         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1110         if (ctxt == NULL) {
1111                 CERROR("can't get appropriate context\n");
1112                 GOTO(out, rc = -EINVAL);
1113         }
1114
1115         llh = ctxt->loc_handle;
1116         if (llh == NULL) {
1117                 CERROR("can't get llh\n");
1118                 llog_ctxt_put(ctxt);
1119                 GOTO(out, rc = -EINVAL);
1120         }
1121
1122         rc = llog_cat_process(&env, llh, osp_sync_process_queues, d, 0, 0);
1123         LASSERTF(rc == 0 || rc == LLOG_PROC_BREAK,
1124                  "%lu changes, %u in progress, %u in flight: %d\n",
1125                  d->opd_syn_changes, d->opd_syn_rpc_in_progress,
1126                  d->opd_syn_rpc_in_flight, rc);
1127
1128         /* we don't expect llog_process_thread() to exit till umount */
1129         LASSERTF(thread->t_flags != SVC_RUNNING,
1130                  "%lu changes, %u in progress, %u in flight\n",
1131                  d->opd_syn_changes, d->opd_syn_rpc_in_progress,
1132                  d->opd_syn_rpc_in_flight);
1133
1134         /* wait till all the requests are completed */
1135         count = 0;
1136         while (d->opd_syn_rpc_in_progress > 0) {
1137                 osp_sync_process_committed(&env, d);
1138
1139                 lwi = LWI_TIMEOUT(cfs_time_seconds(5), NULL, NULL);
1140                 rc = l_wait_event(d->opd_syn_waitq,
1141                                   d->opd_syn_rpc_in_progress == 0,
1142                                   &lwi);
1143                 if (rc == -ETIMEDOUT)
1144                         count++;
1145                 LASSERTF(count < 10, "%s: %d %d %sempty\n",
1146                          d->opd_obd->obd_name, d->opd_syn_rpc_in_progress,
1147                          d->opd_syn_rpc_in_flight,
1148                          list_empty(&d->opd_syn_committed_there) ? "" : "!");
1149
1150         }
1151
1152         llog_cat_close(&env, llh);
1153         rc = llog_cleanup(&env, ctxt);
1154         if (rc)
1155                 CERROR("can't cleanup llog: %d\n", rc);
1156 out:
1157         LASSERTF(d->opd_syn_rpc_in_progress == 0,
1158                  "%s: %d %d %sempty\n",
1159                  d->opd_obd->obd_name, d->opd_syn_rpc_in_progress,
1160                  d->opd_syn_rpc_in_flight,
1161                  list_empty(&d->opd_syn_committed_there) ? "" : "!");
1162
1163         thread->t_flags = SVC_STOPPED;
1164
1165         wake_up(&thread->t_ctl_waitq);
1166
1167         lu_env_fini(&env);
1168
1169         RETURN(0);
1170 }
1171
1172 /**
1173  * Initialize llog.
1174  *
1175  * Initializes the llog. Specific llog to be used depends on the type of the
1176  * target OSP represents (OST or MDT). The function adds appends a new llog
1177  * record to mark the place where the records associated with this boot
1178  * start.
1179  *
1180  * \param[in] env       LU environment provided by the caller
1181  * \param[in] d         OSP device
1182  *
1183  * \retval 0            on success
1184  * \retval negative     negated errno on error
1185  */
1186 static int osp_sync_llog_init(const struct lu_env *env, struct osp_device *d)
1187 {
1188         struct osp_thread_info  *osi = osp_env_info(env);
1189         struct lu_fid           *fid = &osi->osi_fid;
1190         struct llog_handle      *lgh = NULL;
1191         struct obd_device       *obd = d->opd_obd;
1192         struct llog_ctxt        *ctxt;
1193         int                     rc;
1194
1195         ENTRY;
1196
1197         LASSERT(obd);
1198
1199         /*
1200          * open llog corresponding to our OST
1201          */
1202         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1203         obd->obd_lvfs_ctxt.dt = d->opd_storage;
1204
1205         lu_local_obj_fid(fid, LLOG_CATALOGS_OID);
1206
1207         rc = llog_osd_get_cat_list(env, d->opd_storage, d->opd_index, 1,
1208                                    &osi->osi_cid, fid);
1209         if (rc < 0) {
1210                 if (rc != -EFAULT) {
1211                         CERROR("%s: can't get id from catalogs: rc = %d\n",
1212                                obd->obd_name, rc);
1213                         RETURN(rc);
1214                 }
1215
1216                 /* After sparse OST indices is supported, the CATALOG file
1217                  * may become a sparse file that results in failure on
1218                  * reading. Skip this error as the llog will be created
1219                  * later */
1220                 memset(&osi->osi_cid, 0, sizeof(osi->osi_cid));
1221                 rc = 0;
1222         }
1223
1224         CDEBUG(D_INFO, "%s: Init llog for %d - catid "DOSTID":%x\n",
1225                obd->obd_name, d->opd_index,
1226                POSTID(&osi->osi_cid.lci_logid.lgl_oi),
1227                osi->osi_cid.lci_logid.lgl_ogen);
1228
1229         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_MDS_OST_ORIG_CTXT,
1230                         d->opd_storage->dd_lu_dev.ld_obd,
1231                         &osp_mds_ost_orig_logops);
1232         if (rc)
1233                 RETURN(rc);
1234
1235         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1236         LASSERT(ctxt);
1237
1238         if (likely(logid_id(&osi->osi_cid.lci_logid) != 0)) {
1239                 rc = llog_open(env, ctxt, &lgh, &osi->osi_cid.lci_logid, NULL,
1240                                LLOG_OPEN_EXISTS);
1241                 /* re-create llog if it is missing */
1242                 if (rc == -ENOENT)
1243                         logid_set_id(&osi->osi_cid.lci_logid, 0);
1244                 else if (rc < 0)
1245                         GOTO(out_cleanup, rc);
1246         }
1247
1248         if (unlikely(logid_id(&osi->osi_cid.lci_logid) == 0)) {
1249                 rc = llog_open_create(env, ctxt, &lgh, NULL, NULL);
1250                 if (rc < 0)
1251                         GOTO(out_cleanup, rc);
1252                 osi->osi_cid.lci_logid = lgh->lgh_id;
1253         }
1254
1255         LASSERT(lgh != NULL);
1256         ctxt->loc_handle = lgh;
1257
1258         rc = llog_cat_init_and_process(env, lgh);
1259         if (rc)
1260                 GOTO(out_close, rc);
1261
1262         rc = llog_osd_put_cat_list(env, d->opd_storage, d->opd_index, 1,
1263                                    &osi->osi_cid, fid);
1264         if (rc)
1265                 GOTO(out_close, rc);
1266
1267         /*
1268          * put a mark in the llog till which we'll be processing
1269          * old records restless
1270          */
1271         d->opd_syn_generation.mnt_cnt = cfs_time_current();
1272         d->opd_syn_generation.conn_cnt = cfs_time_current();
1273
1274         osi->osi_hdr.lrh_type = LLOG_GEN_REC;
1275         osi->osi_hdr.lrh_len = sizeof(osi->osi_gen);
1276
1277         memcpy(&osi->osi_gen.lgr_gen, &d->opd_syn_generation,
1278                sizeof(osi->osi_gen.lgr_gen));
1279
1280         rc = llog_cat_add(env, lgh, &osi->osi_gen.lgr_hdr, &osi->osi_cookie);
1281         if (rc < 0)
1282                 GOTO(out_close, rc);
1283         llog_ctxt_put(ctxt);
1284         RETURN(0);
1285 out_close:
1286         llog_cat_close(env, lgh);
1287 out_cleanup:
1288         llog_cleanup(env, ctxt);
1289         RETURN(rc);
1290 }
1291
1292 /**
1293  * Cleanup llog used for syncing.
1294  *
1295  * Closes and cleanups the llog. The function is called when the device is
1296  * shutting down.
1297  *
1298  * \param[in] env       LU environment provided by the caller
1299  * \param[in] d         OSP device
1300  */
1301 static void osp_sync_llog_fini(const struct lu_env *env, struct osp_device *d)
1302 {
1303         struct llog_ctxt *ctxt;
1304
1305         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
1306         if (ctxt != NULL)
1307                 llog_cat_close(env, ctxt->loc_handle);
1308         llog_cleanup(env, ctxt);
1309 }
1310
1311 /**
1312  * Initialization of the sync component of OSP.
1313  *
1314  * Initializes the llog and starts a new thread to handle the changes to
1315  * the remote target (OST or MDT).
1316  *
1317  * \param[in] env       LU environment provided by the caller
1318  * \param[in] d         OSP device
1319  *
1320  * \retval 0            on success
1321  * \retval negative     negated errno on error
1322  */
1323 int osp_sync_init(const struct lu_env *env, struct osp_device *d)
1324 {
1325         struct l_wait_info       lwi = { 0 };
1326         struct task_struct      *task;
1327         int                      rc;
1328
1329         ENTRY;
1330
1331         rc = osp_sync_id_traction_init(d);
1332         if (rc)
1333                 RETURN(rc);
1334
1335         /*
1336          * initialize llog storing changes
1337          */
1338         rc = osp_sync_llog_init(env, d);
1339         if (rc) {
1340                 CERROR("%s: can't initialize llog: rc = %d\n",
1341                        d->opd_obd->obd_name, rc);
1342                 GOTO(err_id, rc);
1343         }
1344
1345         /*
1346          * Start synchronization thread
1347          */
1348         d->opd_syn_max_rpc_in_flight = OSP_MAX_IN_FLIGHT;
1349         d->opd_syn_max_rpc_in_progress = OSP_MAX_IN_PROGRESS;
1350         spin_lock_init(&d->opd_syn_lock);
1351         init_waitqueue_head(&d->opd_syn_waitq);
1352         init_waitqueue_head(&d->opd_syn_barrier_waitq);
1353         init_waitqueue_head(&d->opd_syn_thread.t_ctl_waitq);
1354         INIT_LIST_HEAD(&d->opd_syn_committed_there);
1355
1356         task = kthread_run(osp_sync_thread, d, "osp-syn-%u-%u",
1357                            d->opd_index, d->opd_group);
1358         if (IS_ERR(task)) {
1359                 rc = PTR_ERR(task);
1360                 CERROR("%s: cannot start sync thread: rc = %d\n",
1361                        d->opd_obd->obd_name, rc);
1362                 GOTO(err_llog, rc);
1363         }
1364
1365         l_wait_event(d->opd_syn_thread.t_ctl_waitq,
1366                      osp_sync_running(d) || osp_sync_stopped(d), &lwi);
1367
1368         RETURN(0);
1369 err_llog:
1370         osp_sync_llog_fini(env, d);
1371 err_id:
1372         osp_sync_id_traction_fini(d);
1373         return rc;
1374 }
1375
1376 /**
1377  * Stop the syncing thread.
1378  *
1379  * Asks the syncing thread to stop and wait until it's stopped.
1380  *
1381  * \param[in] d         OSP device
1382  *
1383  * \retval              0
1384  */
1385 int osp_sync_fini(struct osp_device *d)
1386 {
1387         struct ptlrpc_thread *thread = &d->opd_syn_thread;
1388
1389         ENTRY;
1390
1391         thread->t_flags = SVC_STOPPING;
1392         wake_up(&d->opd_syn_waitq);
1393         wait_event(thread->t_ctl_waitq, thread->t_flags & SVC_STOPPED);
1394
1395         /*
1396          * unregister transaction callbacks only when sync thread
1397          * has finished operations with llog
1398          */
1399         osp_sync_id_traction_fini(d);
1400
1401         RETURN(0);
1402 }
1403
1404 static DEFINE_MUTEX(osp_id_tracker_sem);
1405 static struct list_head osp_id_tracker_list =
1406                 LIST_HEAD_INIT(osp_id_tracker_list);
1407
1408 /**
1409  * OSD commit callback.
1410  *
1411  * The function is used as a local OSD commit callback to track the highest
1412  * committed llog record id. see osp_sync_id_traction_init() for the details.
1413  *
1414  * \param[in] th        local transaction handle committed
1415  * \param[in] cookie    commit callback data (our private structure)
1416  */
1417 static void osp_sync_tracker_commit_cb(struct thandle *th, void *cookie)
1418 {
1419         struct osp_id_tracker   *tr = cookie;
1420         struct osp_device       *d;
1421         struct osp_txn_info     *txn;
1422
1423         LASSERT(tr);
1424
1425         txn = osp_txn_info(&th->th_ctx);
1426         if (txn == NULL || txn->oti_current_id < tr->otr_committed_id)
1427                 return;
1428
1429         spin_lock(&tr->otr_lock);
1430         if (likely(txn->oti_current_id > tr->otr_committed_id)) {
1431                 CDEBUG(D_OTHER, "committed: %u -> %u\n",
1432                        tr->otr_committed_id, txn->oti_current_id);
1433                 tr->otr_committed_id = txn->oti_current_id;
1434
1435                 list_for_each_entry(d, &tr->otr_wakeup_list,
1436                                     opd_syn_ontrack) {
1437                         d->opd_syn_last_committed_id = tr->otr_committed_id;
1438                         wake_up(&d->opd_syn_waitq);
1439                 }
1440         }
1441         spin_unlock(&tr->otr_lock);
1442 }
1443
1444 /**
1445  * Initialize commit tracking mechanism.
1446  *
1447  * Some setups may have thousands of OSTs and each will be represented by OSP.
1448  * Meaning order of magnitute many more changes to apply every second. In order
1449  * to keep the number of commit callbacks low this mechanism was introduced.
1450  * The mechanism is very similar to transno used by MDT service: it's an single
1451  * ID stream which can be assigned by any OSP to its llog records. The tricky
1452  * part is that ID is stored in per-transaction data and re-used by all the OSPs
1453  * involved in that transaction. Then all these OSPs are woken up utilizing a single OSD commit callback.
1454  *
1455  * The function initializes the data used by the tracker described above.
1456  * A singler tracker per OSD device is created.
1457  *
1458  * \param[in] d         OSP device
1459  *
1460  * \retval 0            on success
1461  * \retval negative     negated errno on error
1462  */
1463 static int osp_sync_id_traction_init(struct osp_device *d)
1464 {
1465         struct osp_id_tracker   *tr, *found = NULL;
1466         int                      rc = 0;
1467
1468         LASSERT(d);
1469         LASSERT(d->opd_storage);
1470         LASSERT(d->opd_syn_tracker == NULL);
1471         INIT_LIST_HEAD(&d->opd_syn_ontrack);
1472
1473         mutex_lock(&osp_id_tracker_sem);
1474         list_for_each_entry(tr, &osp_id_tracker_list, otr_list) {
1475                 if (tr->otr_dev == d->opd_storage) {
1476                         LASSERT(atomic_read(&tr->otr_refcount));
1477                         atomic_inc(&tr->otr_refcount);
1478                         d->opd_syn_tracker = tr;
1479                         found = tr;
1480                         break;
1481                 }
1482         }
1483
1484         if (found == NULL) {
1485                 rc = -ENOMEM;
1486                 OBD_ALLOC_PTR(tr);
1487                 if (tr) {
1488                         d->opd_syn_tracker = tr;
1489                         spin_lock_init(&tr->otr_lock);
1490                         tr->otr_dev = d->opd_storage;
1491                         tr->otr_next_id = 1;
1492                         tr->otr_committed_id = 0;
1493                         atomic_set(&tr->otr_refcount, 1);
1494                         INIT_LIST_HEAD(&tr->otr_wakeup_list);
1495                         list_add(&tr->otr_list, &osp_id_tracker_list);
1496                         tr->otr_tx_cb.dtc_txn_commit =
1497                                                 osp_sync_tracker_commit_cb;
1498                         tr->otr_tx_cb.dtc_cookie = tr;
1499                         tr->otr_tx_cb.dtc_tag = LCT_MD_THREAD;
1500                         dt_txn_callback_add(d->opd_storage, &tr->otr_tx_cb);
1501                         rc = 0;
1502                 }
1503         }
1504         mutex_unlock(&osp_id_tracker_sem);
1505
1506         return rc;
1507 }
1508
1509 /**
1510  * Release commit tracker.
1511  *
1512  * Decrease a refcounter on the tracker used by the given OSP device \a d.
1513  * If no more users left, then the tracker is released.
1514  *
1515  * \param[in] d         OSP device
1516  */
1517 static void osp_sync_id_traction_fini(struct osp_device *d)
1518 {
1519         struct osp_id_tracker *tr;
1520
1521         ENTRY;
1522
1523         LASSERT(d);
1524         tr = d->opd_syn_tracker;
1525         if (tr == NULL) {
1526                 EXIT;
1527                 return;
1528         }
1529
1530         osp_sync_remove_from_tracker(d);
1531
1532         mutex_lock(&osp_id_tracker_sem);
1533         if (atomic_dec_and_test(&tr->otr_refcount)) {
1534                 dt_txn_callback_del(d->opd_storage, &tr->otr_tx_cb);
1535                 LASSERT(list_empty(&tr->otr_wakeup_list));
1536                 list_del(&tr->otr_list);
1537                 OBD_FREE_PTR(tr);
1538                 d->opd_syn_tracker = NULL;
1539         }
1540         mutex_unlock(&osp_id_tracker_sem);
1541
1542         EXIT;
1543 }
1544
1545 /**
1546  * Generate a new ID on a tracker.
1547  *
1548  * Generates a new ID using the tracker associated with the given OSP device
1549  * \a d, if the given ID \a id is non-zero. Unconditially adds OSP device to
1550  * the wakeup list, so OSP won't miss when a transaction using the ID is
1551  * committed. Notice ID is 32bit, but llog doesn't support >2^32 records anyway.
1552  *
1553  * \param[in] d         OSP device
1554  * \param[in] id        0 or ID generated previously
1555  *
1556  * \retval              ID the caller should use
1557  */
1558 static __u32 osp_sync_id_get(struct osp_device *d, __u32 id)
1559 {
1560         struct osp_id_tracker *tr;
1561
1562         tr = d->opd_syn_tracker;
1563         LASSERT(tr);
1564
1565         /* XXX: we can improve this introducing per-cpu preallocated ids? */
1566         spin_lock(&tr->otr_lock);
1567         if (unlikely(tr->otr_next_id <= d->opd_syn_last_used_id)) {
1568                 spin_unlock(&tr->otr_lock);
1569                 CERROR("%s: next %u, last synced %lu\n",
1570                        d->opd_obd->obd_name, tr->otr_next_id,
1571                        d->opd_syn_last_used_id);
1572                 LBUG();
1573         }
1574
1575         if (id == 0)
1576                 id = tr->otr_next_id++;
1577         if (id > d->opd_syn_last_used_id)
1578                 d->opd_syn_last_used_id = id;
1579         if (list_empty(&d->opd_syn_ontrack))
1580                 list_add(&d->opd_syn_ontrack, &tr->otr_wakeup_list);
1581         spin_unlock(&tr->otr_lock);
1582         CDEBUG(D_OTHER, "new id %u\n", (unsigned) id);
1583
1584         return id;
1585 }
1586
1587 /**
1588  * Stop to propagate commit status to OSP.
1589  *
1590  * If the OSP does not have any llog records she's waiting to commit, then
1591  * it is possible to unsubscribe from wakeups from the tracking using this
1592  * method.
1593  *
1594  * \param[in] d         OSP device not willing to wakeup
1595  */
1596 static void osp_sync_remove_from_tracker(struct osp_device *d)
1597 {
1598         struct osp_id_tracker *tr;
1599
1600         tr = d->opd_syn_tracker;
1601         LASSERT(tr);
1602
1603         if (list_empty(&d->opd_syn_ontrack))
1604                 return;
1605
1606         spin_lock(&tr->otr_lock);
1607         list_del_init(&d->opd_syn_ontrack);
1608         spin_unlock(&tr->otr_lock);
1609 }
1610