Whamcloud - gitweb
f0d785a6fe3456ef5f14b6ceb418b8e905cc05b9
[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         req = ptlrpc_request_alloc(imp, format);
595         if (req == NULL)
596                 RETURN(ERR_PTR(-ENOMEM));
597
598         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, op);
599         if (rc) {
600                 ptlrpc_req_finished(req);
601                 return ERR_PTR(rc);
602         }
603
604         /*
605          * this is a trick: to save on memory allocations we put cookie
606          * into the request, but don't set corresponded flag in o_valid
607          * so that OST doesn't interpret this cookie. once the request
608          * is committed on OST we take cookie from the request and cancel
609          */
610         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
611         LASSERT(body);
612         body->oa.o_lcookie.lgc_lgl = llh->lgh_id;
613         body->oa.o_lcookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
614         body->oa.o_lcookie.lgc_index = h->lrh_index;
615
616         req->rq_interpret_reply = osp_sync_interpret;
617         req->rq_commit_cb = osp_sync_request_commit_cb;
618         req->rq_cb_data = d;
619
620         ptlrpc_request_set_replen(req);
621
622         return req;
623 }
624
625 /**
626  * Generate a request for setattr change.
627  *
628  * The function prepares a new RPC, initializes it with setattr specific
629  * bits and send the RPC.
630  *
631  * \param[in] d         OSP device
632  * \param[in] llh       llog handle where the record is stored
633  * \param[in] h         llog record
634  *
635  * \retval 0            on success
636  * \retval negative     negated errno on error
637  */
638 static int osp_sync_new_setattr_job(struct osp_device *d,
639                                     struct llog_handle *llh,
640                                     struct llog_rec_hdr *h)
641 {
642         struct llog_setattr64_rec       *rec = (struct llog_setattr64_rec *)h;
643         struct ptlrpc_request           *req;
644         struct ost_body                 *body;
645
646         ENTRY;
647         LASSERT(h->lrh_type == MDS_SETATTR64_REC);
648
649         /* lsr_valid can only be 0 or have OBD_MD_{FLUID,FLGID} set,
650          * so no bits other than these should be set. */
651         if ((rec->lsr_valid & ~(OBD_MD_FLUID | OBD_MD_FLGID)) != 0) {
652                 CERROR("%s: invalid setattr record, lsr_valid:"LPU64"\n",
653                        d->opd_obd->obd_name, rec->lsr_valid);
654                 /* return 0 so that sync thread can continue processing
655                  * other records. */
656                 RETURN(0);
657         }
658
659         req = osp_sync_new_job(d, llh, h, OST_SETATTR, &RQF_OST_SETATTR);
660         if (IS_ERR(req))
661                 RETURN(PTR_ERR(req));
662
663         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
664         LASSERT(body);
665         body->oa.o_oi = rec->lsr_oi;
666         body->oa.o_uid = rec->lsr_uid;
667         body->oa.o_gid = rec->lsr_gid;
668         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
669         /* old setattr record (prior 2.6.0) doesn't have 'valid' stored,
670          * we assume that both UID and GID are valid in that case. */
671         if (rec->lsr_valid == 0)
672                 body->oa.o_valid |= (OBD_MD_FLUID | OBD_MD_FLGID);
673         else
674                 body->oa.o_valid |= rec->lsr_valid;
675
676         osp_sync_send_new_rpc(d, req);
677         RETURN(1);
678 }
679
680 /**
681  * Generate a request for unlink change.
682  *
683  * The function prepares a new RPC, initializes it with unlink(destroy)
684  * specific bits and sends the RPC. The function is used to handle
685  * llog_unlink_rec which were used in the older versions of Lustre.
686  * Current version uses llog_unlink_rec64.
687  *
688  * \param[in] d         OSP device
689  * \param[in] llh       llog handle where the record is stored
690  * \param[in] h         llog record
691  *
692  * \retval 0            on success
693  * \retval negative     negated errno on error
694  */
695 static int osp_sync_new_unlink_job(struct osp_device *d,
696                                    struct llog_handle *llh,
697                                    struct llog_rec_hdr *h)
698 {
699         struct llog_unlink_rec  *rec = (struct llog_unlink_rec *)h;
700         struct ptlrpc_request   *req;
701         struct ost_body         *body;
702
703         ENTRY;
704         LASSERT(h->lrh_type == MDS_UNLINK_REC);
705
706         req = osp_sync_new_job(d, llh, h, OST_DESTROY, &RQF_OST_DESTROY);
707         if (IS_ERR(req))
708                 RETURN(PTR_ERR(req));
709
710         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
711         LASSERT(body);
712         ostid_set_seq(&body->oa.o_oi, rec->lur_oseq);
713         ostid_set_id(&body->oa.o_oi, rec->lur_oid);
714         body->oa.o_misc = rec->lur_count;
715         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
716         if (rec->lur_count)
717                 body->oa.o_valid |= OBD_MD_FLOBJCOUNT;
718
719         osp_sync_send_new_rpc(d, req);
720         RETURN(1);
721 }
722
723 /**
724  * Generate a request for unlink change.
725  *
726  * The function prepares a new RPC, initializes it with unlink(destroy)
727  * specific bits and sends the RPC. Depending on the target (MDT or OST)
728  * two different protocols are used. For MDT we use OUT (basically OSD API
729  * updates transferred via a network). For OST we still use the old
730  * protocol (OBD?), originally for compatibility. Later we can start to
731  * use OUT for OST as well, this will allow batching and better code
732  * unification.
733  *
734  * \param[in] env       LU environment provided by the caller
735  * \param[in] d         OSP device
736  * \param[in] llh       llog handle where the record is stored
737  * \param[in] h         llog record
738  *
739  * \retval 0            on success
740  * \retval negative     negated errno on error
741  */
742 static int osp_sync_new_unlink64_job(const struct lu_env *env,
743                                      struct osp_device *d,
744                                      struct llog_handle *llh,
745                                      struct llog_rec_hdr *h)
746 {
747         struct llog_unlink64_rec        *rec = (struct llog_unlink64_rec *)h;
748         struct ptlrpc_request           *req = NULL;
749         struct ost_body                 *body;
750         int                              rc;
751
752         ENTRY;
753         LASSERT(h->lrh_type == MDS_UNLINK64_REC);
754         req = osp_sync_new_job(d, llh, h, OST_DESTROY,
755                                &RQF_OST_DESTROY);
756         if (IS_ERR(req))
757                 RETURN(PTR_ERR(req));
758
759         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
760         if (body == NULL)
761                 RETURN(-EFAULT);
762         rc = fid_to_ostid(&rec->lur_fid, &body->oa.o_oi);
763         if (rc < 0)
764                 RETURN(rc);
765         body->oa.o_misc = rec->lur_count;
766         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID |
767                            OBD_MD_FLOBJCOUNT;
768         osp_sync_send_new_rpc(d, req);
769         RETURN(1);
770 }
771
772 /**
773  * Process llog records.
774  *
775  * This function is called to process the llog records committed locally.
776  * In the recovery model used by OSP we can apply a change to a remote
777  * target once corresponding transaction (like posix unlink) is committed
778  * locally so can't revert.
779  * Depending on the llog record type, a given handler is called that is
780  * responsible for preparing and sending the RPC to apply the change.
781  * Special record type LLOG_GEN_REC marking a reboot is cancelled right away.
782  *
783  * \param[in] env       LU environment provided by the caller
784  * \param[in] d         OSP device
785  * \param[in] llh       llog handle where the record is stored
786  * \param[in] rec       llog record
787  *
788  * \retval 0            on success
789  * \retval negative     negated errno on error
790  */
791 static int osp_sync_process_record(const struct lu_env *env,
792                                    struct osp_device *d,
793                                    struct llog_handle *llh,
794                                    struct llog_rec_hdr *rec)
795 {
796         struct llog_cookie       cookie;
797         int                      rc = 0;
798
799         cookie.lgc_lgl = llh->lgh_id;
800         cookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
801         cookie.lgc_index = rec->lrh_index;
802
803         if (unlikely(rec->lrh_type == LLOG_GEN_REC)) {
804                 struct llog_gen_rec *gen = (struct llog_gen_rec *)rec;
805
806                 /* we're waiting for the record generated by this instance */
807                 LASSERT(d->opd_syn_prev_done == 0);
808                 if (!memcmp(&d->opd_syn_generation, &gen->lgr_gen,
809                             sizeof(gen->lgr_gen))) {
810                         CDEBUG(D_HA, "processed all old entries\n");
811                         d->opd_syn_prev_done = 1;
812                 }
813
814                 /* cancel any generation record */
815                 rc = llog_cat_cancel_records(env, llh->u.phd.phd_cat_handle,
816                                              1, &cookie);
817
818                 return rc;
819         }
820
821         /*
822          * now we prepare and fill requests to OST, put them on the queue
823          * and fire after next commit callback
824          */
825
826         /* notice we increment counters before sending RPC, to be consistent
827          * in RPC interpret callback which may happen very quickly */
828         spin_lock(&d->opd_syn_lock);
829         d->opd_syn_rpc_in_flight++;
830         d->opd_syn_rpc_in_progress++;
831         spin_unlock(&d->opd_syn_lock);
832
833         switch (rec->lrh_type) {
834         /* case MDS_UNLINK_REC is kept for compatibility */
835         case MDS_UNLINK_REC:
836                 rc = osp_sync_new_unlink_job(d, llh, rec);
837                 break;
838         case MDS_UNLINK64_REC:
839                 rc = osp_sync_new_unlink64_job(env, d, llh, rec);
840                 break;
841         case MDS_SETATTR64_REC:
842                 rc = osp_sync_new_setattr_job(d, llh, rec);
843                 break;
844         default:
845                 CERROR("%s: unknown record type: %x\n", d->opd_obd->obd_name,
846                        rec->lrh_type);
847                 /* we should continue processing */
848         }
849
850         /* rc > 0 means sync RPC being added to the queue */
851         if (likely(rc > 0)) {
852                 spin_lock(&d->opd_syn_lock);
853                 if (d->opd_syn_prev_done) {
854                         LASSERT(d->opd_syn_changes > 0);
855                         LASSERT(rec->lrh_id <= d->opd_syn_last_committed_id);
856                         /*
857                          * NOTE: it's possible to meet same id if
858                          * OST stores few stripes of same file
859                          */
860                         if (rec->lrh_id > d->opd_syn_last_processed_id) {
861                                 d->opd_syn_last_processed_id = rec->lrh_id;
862                                 wake_up(&d->opd_syn_barrier_waitq);
863                         }
864
865                         d->opd_syn_changes--;
866                 }
867                 CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
868                        d->opd_obd->obd_name, d->opd_syn_rpc_in_flight,
869                        d->opd_syn_rpc_in_progress);
870                 spin_unlock(&d->opd_syn_lock);
871                 rc = 0;
872         } else {
873                 spin_lock(&d->opd_syn_lock);
874                 d->opd_syn_rpc_in_flight--;
875                 d->opd_syn_rpc_in_progress--;
876                 spin_unlock(&d->opd_syn_lock);
877         }
878
879         CDEBUG(D_HA, "found record %x, %d, idx %u, id %u: %d\n",
880                rec->lrh_type, rec->lrh_len, rec->lrh_index, rec->lrh_id, rc);
881         return rc;
882 }
883
884 /**
885  * Cancel llog records for the committed changes.
886  *
887  * The function walks through the list of the committed RPCs and cancels
888  * corresponding llog records. see osp_sync_request_commit_cb() for the
889  * details.
890  *
891  * \param[in] env       LU environment provided by the caller
892  * \param[in] d         OSP device
893  */
894 static void osp_sync_process_committed(const struct lu_env *env,
895                                        struct osp_device *d)
896 {
897         struct obd_device       *obd = d->opd_obd;
898         struct obd_import       *imp = obd->u.cli.cl_import;
899         struct ost_body         *body;
900         struct ptlrpc_request   *req;
901         struct llog_ctxt        *ctxt;
902         struct llog_handle      *llh;
903         struct list_head         list;
904         int                      rc, done = 0;
905
906         ENTRY;
907
908         if (list_empty(&d->opd_syn_committed_there))
909                 return;
910
911         /*
912          * if current status is -ENOSPC (lack of free space on OST)
913          * then we should poll OST immediately once object destroy
914          * is committed.
915          * notice: we do this upon commit as well because some backends
916          * (like DMU) do not release space right away.
917          */
918         if (d->opd_pre != NULL && unlikely(d->opd_pre_status == -ENOSPC))
919                 osp_statfs_need_now(d);
920
921         /*
922          * now cancel them all
923          * XXX: can we improve this using some batching?
924          *      with batch RPC that'll happen automatically?
925          * XXX: can we store ctxt in lod_device and save few cycles ?
926          */
927         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
928         LASSERT(ctxt);
929
930         llh = ctxt->loc_handle;
931         LASSERT(llh);
932
933         INIT_LIST_HEAD(&list);
934         spin_lock(&d->opd_syn_lock);
935         list_splice(&d->opd_syn_committed_there, &list);
936         INIT_LIST_HEAD(&d->opd_syn_committed_there);
937         spin_unlock(&d->opd_syn_lock);
938
939         while (!list_empty(&list)) {
940                 struct llog_cookie *lcookie = NULL;
941                 struct osp_job_req_args *jra;
942
943                 jra = list_entry(list.next, struct osp_job_req_args, jra_link);
944                 LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
945                 list_del_init(&jra->jra_link);
946
947                 req = container_of((void *)jra, struct ptlrpc_request,
948                                    rq_async_args);
949                 body = req_capsule_client_get(&req->rq_pill,
950                                               &RMF_OST_BODY);
951                 LASSERT(body);
952                 lcookie = &body->oa.o_lcookie;
953                 /* import can be closing, thus all commit cb's are
954                  * called we can check committness directly */
955                 if (req->rq_transno <= imp->imp_peer_committed_transno) {
956                         rc = llog_cat_cancel_records(env, llh, 1, lcookie);
957                         if (rc)
958                                 CERROR("%s: can't cancel record: %d\n",
959                                        obd->obd_name, rc);
960                 } else {
961                         DEBUG_REQ(D_HA, req, "not committed");
962                 }
963
964                 ptlrpc_req_finished(req);
965                 done++;
966         }
967
968         llog_ctxt_put(ctxt);
969
970         LASSERT(d->opd_syn_rpc_in_progress >= done);
971         spin_lock(&d->opd_syn_lock);
972         d->opd_syn_rpc_in_progress -= done;
973         spin_unlock(&d->opd_syn_lock);
974         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
975                d->opd_obd->obd_name, d->opd_syn_rpc_in_flight,
976                d->opd_syn_rpc_in_progress);
977
978         osp_sync_check_for_work(d);
979
980         /* wake up the thread if requested to stop:
981          * it might be waiting for in-progress to complete */
982         if (unlikely(osp_sync_running(d) == 0))
983                 wake_up(&d->opd_syn_waitq);
984
985         EXIT;
986 }
987
988 /**
989  * The core of the syncing mechanism.
990  *
991  * This is a callback called by the llog processing function. Essentially it
992  * suspends llog processing until there is a record to process (it's supposed
993  * to be committed locally). The function handles RPCs committed by the target
994  * and cancels corresponding llog records.
995  *
996  * \param[in] env       LU environment provided by the caller
997  * \param[in] llh       llog handle we're processing
998  * \param[in] rec       current llog record
999  * \param[in] data      callback data containing a pointer to the device
1000  *
1001  * \retval 0                    to ask the caller (llog_process()) to continue
1002  * \retval LLOG_PROC_BREAK      to ask the caller to break
1003  */
1004 static int osp_sync_process_queues(const struct lu_env *env,
1005                                    struct llog_handle *llh,
1006                                    struct llog_rec_hdr *rec,
1007                                    void *data)
1008 {
1009         struct osp_device       *d = data;
1010         int                      rc;
1011
1012         do {
1013                 struct l_wait_info lwi = { 0 };
1014
1015                 if (!osp_sync_running(d)) {
1016                         CDEBUG(D_HA, "stop llog processing\n");
1017                         return LLOG_PROC_BREAK;
1018                 }
1019
1020                 /* process requests committed by OST */
1021                 osp_sync_process_committed(env, d);
1022
1023                 /* if we there are changes to be processed and we have
1024                  * resources for this ... do now */
1025                 if (osp_sync_can_process_new(d, rec)) {
1026                         if (llh == NULL) {
1027                                 /* ask llog for another record */
1028                                 CDEBUG(D_HA, "%lu changes, %u in progress,"
1029                                        " %u in flight\n",
1030                                        d->opd_syn_changes,
1031                                        d->opd_syn_rpc_in_progress,
1032                                        d->opd_syn_rpc_in_flight);
1033                                 return 0;
1034                         }
1035
1036                         /*
1037                          * try to send, in case of disconnection, suspend
1038                          * processing till we can send this request
1039                          */
1040                         do {
1041                                 rc = osp_sync_process_record(env, d, llh, rec);
1042                                 /*
1043                                  * XXX: probably different handling is needed
1044                                  * for some bugs, like immediate exit or if
1045                                  * OSP gets inactive
1046                                  */
1047                                 if (rc) {
1048                                         CERROR("can't send: %d\n", rc);
1049                                         l_wait_event(d->opd_syn_waitq,
1050                                                      !osp_sync_running(d) ||
1051                                                      osp_sync_has_work(d),
1052                                                      &lwi);
1053                                 }
1054                         } while (rc != 0 && osp_sync_running(d));
1055
1056                         llh = NULL;
1057                         rec = NULL;
1058                 }
1059
1060                 if (d->opd_syn_last_processed_id == d->opd_syn_last_used_id)
1061                         osp_sync_remove_from_tracker(d);
1062
1063                 l_wait_event(d->opd_syn_waitq,
1064                              !osp_sync_running(d) ||
1065                              osp_sync_can_process_new(d, rec) ||
1066                              !list_empty(&d->opd_syn_committed_there),
1067                              &lwi);
1068         } while (1);
1069 }
1070
1071 /**
1072  * OSP sync thread.
1073  *
1074  * This thread runs llog_cat_process() scanner calling our callback
1075  * to process llog records. in the callback we implement tricky
1076  * state machine as we don't want to start scanning of the llog again
1077  * and again, also we don't want to process too many records and send
1078  * too many RPCs a time. so, depending on current load (num of changes
1079  * being synced to OST) the callback can suspend awaiting for some
1080  * new conditions, like syncs completed.
1081  *
1082  * In order to process llog records left by previous boots and to allow
1083  * llog_process_thread() to find something (otherwise it'd just exit
1084  * immediately) we add a special GENERATATION record on each boot.
1085  *
1086  * \param[in] _arg      a pointer to thread's arguments
1087  *
1088  * \retval 0            on success
1089  * \retval negative     negated errno on error
1090  */
1091 static int osp_sync_thread(void *_arg)
1092 {
1093         struct osp_device       *d = _arg;
1094         struct ptlrpc_thread    *thread = &d->opd_syn_thread;
1095         struct l_wait_info       lwi = { 0 };
1096         struct llog_ctxt        *ctxt;
1097         struct obd_device       *obd = d->opd_obd;
1098         struct llog_handle      *llh;
1099         struct lu_env            env;
1100         int                      rc, count;
1101
1102         ENTRY;
1103
1104         rc = lu_env_init(&env, LCT_LOCAL);
1105         if (rc) {
1106                 CERROR("%s: can't initialize env: rc = %d\n",
1107                        obd->obd_name, rc);
1108                 RETURN(rc);
1109         }
1110
1111         spin_lock(&d->opd_syn_lock);
1112         thread->t_flags = SVC_RUNNING;
1113         spin_unlock(&d->opd_syn_lock);
1114         wake_up(&thread->t_ctl_waitq);
1115
1116         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1117         if (ctxt == NULL) {
1118                 CERROR("can't get appropriate context\n");
1119                 GOTO(out, rc = -EINVAL);
1120         }
1121
1122         llh = ctxt->loc_handle;
1123         if (llh == NULL) {
1124                 CERROR("can't get llh\n");
1125                 llog_ctxt_put(ctxt);
1126                 GOTO(out, rc = -EINVAL);
1127         }
1128
1129         rc = llog_cat_process(&env, llh, osp_sync_process_queues, d, 0, 0);
1130         LASSERTF(rc == 0 || rc == LLOG_PROC_BREAK,
1131                  "%lu changes, %u in progress, %u in flight: %d\n",
1132                  d->opd_syn_changes, d->opd_syn_rpc_in_progress,
1133                  d->opd_syn_rpc_in_flight, rc);
1134
1135         /* we don't expect llog_process_thread() to exit till umount */
1136         LASSERTF(thread->t_flags != SVC_RUNNING,
1137                  "%lu changes, %u in progress, %u in flight\n",
1138                  d->opd_syn_changes, d->opd_syn_rpc_in_progress,
1139                  d->opd_syn_rpc_in_flight);
1140
1141         /* wait till all the requests are completed */
1142         count = 0;
1143         while (d->opd_syn_rpc_in_progress > 0) {
1144                 osp_sync_process_committed(&env, d);
1145
1146                 lwi = LWI_TIMEOUT(cfs_time_seconds(5), NULL, NULL);
1147                 rc = l_wait_event(d->opd_syn_waitq,
1148                                   d->opd_syn_rpc_in_progress == 0,
1149                                   &lwi);
1150                 if (rc == -ETIMEDOUT)
1151                         count++;
1152                 LASSERTF(count < 10, "%s: %d %d %sempty\n",
1153                          d->opd_obd->obd_name, d->opd_syn_rpc_in_progress,
1154                          d->opd_syn_rpc_in_flight,
1155                          list_empty(&d->opd_syn_committed_there) ? "" : "!");
1156
1157         }
1158
1159         llog_cat_close(&env, llh);
1160         rc = llog_cleanup(&env, ctxt);
1161         if (rc)
1162                 CERROR("can't cleanup llog: %d\n", rc);
1163 out:
1164         LASSERTF(d->opd_syn_rpc_in_progress == 0,
1165                  "%s: %d %d %sempty\n",
1166                  d->opd_obd->obd_name, d->opd_syn_rpc_in_progress,
1167                  d->opd_syn_rpc_in_flight,
1168                  list_empty(&d->opd_syn_committed_there) ? "" : "!");
1169
1170         thread->t_flags = SVC_STOPPED;
1171
1172         wake_up(&thread->t_ctl_waitq);
1173
1174         lu_env_fini(&env);
1175
1176         RETURN(0);
1177 }
1178
1179 /**
1180  * Initialize llog.
1181  *
1182  * Initializes the llog. Specific llog to be used depends on the type of the
1183  * target OSP represents (OST or MDT). The function adds appends a new llog
1184  * record to mark the place where the records associated with this boot
1185  * start.
1186  *
1187  * \param[in] env       LU environment provided by the caller
1188  * \param[in] d         OSP device
1189  *
1190  * \retval 0            on success
1191  * \retval negative     negated errno on error
1192  */
1193 static int osp_sync_llog_init(const struct lu_env *env, struct osp_device *d)
1194 {
1195         struct osp_thread_info  *osi = osp_env_info(env);
1196         struct lu_fid           *fid = &osi->osi_fid;
1197         struct llog_handle      *lgh = NULL;
1198         struct obd_device       *obd = d->opd_obd;
1199         struct llog_ctxt        *ctxt;
1200         int                     rc;
1201
1202         ENTRY;
1203
1204         LASSERT(obd);
1205
1206         /*
1207          * open llog corresponding to our OST
1208          */
1209         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1210         obd->obd_lvfs_ctxt.dt = d->opd_storage;
1211
1212         lu_local_obj_fid(fid, LLOG_CATALOGS_OID);
1213
1214         rc = llog_osd_get_cat_list(env, d->opd_storage, d->opd_index, 1,
1215                                    &osi->osi_cid, fid);
1216         if (rc < 0) {
1217                 if (rc != -EFAULT) {
1218                         CERROR("%s: can't get id from catalogs: rc = %d\n",
1219                                obd->obd_name, rc);
1220                         RETURN(rc);
1221                 }
1222
1223                 /* After sparse OST indices is supported, the CATALOG file
1224                  * may become a sparse file that results in failure on
1225                  * reading. Skip this error as the llog will be created
1226                  * later */
1227                 memset(&osi->osi_cid, 0, sizeof(osi->osi_cid));
1228                 rc = 0;
1229         }
1230
1231         CDEBUG(D_INFO, "%s: Init llog for %d - catid "DOSTID":%x\n",
1232                obd->obd_name, d->opd_index,
1233                POSTID(&osi->osi_cid.lci_logid.lgl_oi),
1234                osi->osi_cid.lci_logid.lgl_ogen);
1235
1236         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_MDS_OST_ORIG_CTXT,
1237                         d->opd_storage->dd_lu_dev.ld_obd,
1238                         &osp_mds_ost_orig_logops);
1239         if (rc)
1240                 RETURN(rc);
1241
1242         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1243         LASSERT(ctxt);
1244
1245         if (likely(logid_id(&osi->osi_cid.lci_logid) != 0)) {
1246                 rc = llog_open(env, ctxt, &lgh, &osi->osi_cid.lci_logid, NULL,
1247                                LLOG_OPEN_EXISTS);
1248                 /* re-create llog if it is missing */
1249                 if (rc == -ENOENT)
1250                         logid_set_id(&osi->osi_cid.lci_logid, 0);
1251                 else if (rc < 0)
1252                         GOTO(out_cleanup, rc);
1253         }
1254
1255         if (unlikely(logid_id(&osi->osi_cid.lci_logid) == 0)) {
1256                 rc = llog_open_create(env, ctxt, &lgh, NULL, NULL);
1257                 if (rc < 0)
1258                         GOTO(out_cleanup, rc);
1259                 osi->osi_cid.lci_logid = lgh->lgh_id;
1260         }
1261
1262         LASSERT(lgh != NULL);
1263         ctxt->loc_handle = lgh;
1264
1265         rc = llog_cat_init_and_process(env, lgh);
1266         if (rc)
1267                 GOTO(out_close, rc);
1268
1269         rc = llog_osd_put_cat_list(env, d->opd_storage, d->opd_index, 1,
1270                                    &osi->osi_cid, fid);
1271         if (rc)
1272                 GOTO(out_close, rc);
1273
1274         /*
1275          * put a mark in the llog till which we'll be processing
1276          * old records restless
1277          */
1278         d->opd_syn_generation.mnt_cnt = cfs_time_current();
1279         d->opd_syn_generation.conn_cnt = cfs_time_current();
1280
1281         osi->osi_hdr.lrh_type = LLOG_GEN_REC;
1282         osi->osi_hdr.lrh_len = sizeof(osi->osi_gen);
1283
1284         memcpy(&osi->osi_gen.lgr_gen, &d->opd_syn_generation,
1285                sizeof(osi->osi_gen.lgr_gen));
1286
1287         rc = llog_cat_add(env, lgh, &osi->osi_gen.lgr_hdr, &osi->osi_cookie);
1288         if (rc < 0)
1289                 GOTO(out_close, rc);
1290         llog_ctxt_put(ctxt);
1291         RETURN(0);
1292 out_close:
1293         llog_cat_close(env, lgh);
1294 out_cleanup:
1295         llog_cleanup(env, ctxt);
1296         RETURN(rc);
1297 }
1298
1299 /**
1300  * Cleanup llog used for syncing.
1301  *
1302  * Closes and cleanups the llog. The function is called when the device is
1303  * shutting down.
1304  *
1305  * \param[in] env       LU environment provided by the caller
1306  * \param[in] d         OSP device
1307  */
1308 static void osp_sync_llog_fini(const struct lu_env *env, struct osp_device *d)
1309 {
1310         struct llog_ctxt *ctxt;
1311
1312         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
1313         if (ctxt != NULL)
1314                 llog_cat_close(env, ctxt->loc_handle);
1315         llog_cleanup(env, ctxt);
1316 }
1317
1318 /**
1319  * Initialization of the sync component of OSP.
1320  *
1321  * Initializes the llog and starts a new thread to handle the changes to
1322  * the remote target (OST or MDT).
1323  *
1324  * \param[in] env       LU environment provided by the caller
1325  * \param[in] d         OSP device
1326  *
1327  * \retval 0            on success
1328  * \retval negative     negated errno on error
1329  */
1330 int osp_sync_init(const struct lu_env *env, struct osp_device *d)
1331 {
1332         struct l_wait_info       lwi = { 0 };
1333         struct task_struct      *task;
1334         int                      rc;
1335
1336         ENTRY;
1337
1338         rc = osp_sync_id_traction_init(d);
1339         if (rc)
1340                 RETURN(rc);
1341
1342         /*
1343          * initialize llog storing changes
1344          */
1345         rc = osp_sync_llog_init(env, d);
1346         if (rc) {
1347                 CERROR("%s: can't initialize llog: rc = %d\n",
1348                        d->opd_obd->obd_name, rc);
1349                 GOTO(err_id, rc);
1350         }
1351
1352         /*
1353          * Start synchronization thread
1354          */
1355         d->opd_syn_max_rpc_in_flight = OSP_MAX_IN_FLIGHT;
1356         d->opd_syn_max_rpc_in_progress = OSP_MAX_IN_PROGRESS;
1357         spin_lock_init(&d->opd_syn_lock);
1358         init_waitqueue_head(&d->opd_syn_waitq);
1359         init_waitqueue_head(&d->opd_syn_barrier_waitq);
1360         init_waitqueue_head(&d->opd_syn_thread.t_ctl_waitq);
1361         INIT_LIST_HEAD(&d->opd_syn_committed_there);
1362
1363         task = kthread_run(osp_sync_thread, d, "osp-syn-%u-%u",
1364                            d->opd_index, d->opd_group);
1365         if (IS_ERR(task)) {
1366                 rc = PTR_ERR(task);
1367                 CERROR("%s: cannot start sync thread: rc = %d\n",
1368                        d->opd_obd->obd_name, rc);
1369                 GOTO(err_llog, rc);
1370         }
1371
1372         l_wait_event(d->opd_syn_thread.t_ctl_waitq,
1373                      osp_sync_running(d) || osp_sync_stopped(d), &lwi);
1374
1375         RETURN(0);
1376 err_llog:
1377         osp_sync_llog_fini(env, d);
1378 err_id:
1379         osp_sync_id_traction_fini(d);
1380         return rc;
1381 }
1382
1383 /**
1384  * Stop the syncing thread.
1385  *
1386  * Asks the syncing thread to stop and wait until it's stopped.
1387  *
1388  * \param[in] d         OSP device
1389  *
1390  * \retval              0
1391  */
1392 int osp_sync_fini(struct osp_device *d)
1393 {
1394         struct ptlrpc_thread *thread = &d->opd_syn_thread;
1395
1396         ENTRY;
1397
1398         thread->t_flags = SVC_STOPPING;
1399         wake_up(&d->opd_syn_waitq);
1400         wait_event(thread->t_ctl_waitq, thread->t_flags & SVC_STOPPED);
1401
1402         /*
1403          * unregister transaction callbacks only when sync thread
1404          * has finished operations with llog
1405          */
1406         osp_sync_id_traction_fini(d);
1407
1408         RETURN(0);
1409 }
1410
1411 static DEFINE_MUTEX(osp_id_tracker_sem);
1412 static struct list_head osp_id_tracker_list =
1413                 LIST_HEAD_INIT(osp_id_tracker_list);
1414
1415 /**
1416  * OSD commit callback.
1417  *
1418  * The function is used as a local OSD commit callback to track the highest
1419  * committed llog record id. see osp_sync_id_traction_init() for the details.
1420  *
1421  * \param[in] th        local transaction handle committed
1422  * \param[in] cookie    commit callback data (our private structure)
1423  */
1424 static void osp_sync_tracker_commit_cb(struct thandle *th, void *cookie)
1425 {
1426         struct osp_id_tracker   *tr = cookie;
1427         struct osp_device       *d;
1428         struct osp_txn_info     *txn;
1429
1430         LASSERT(tr);
1431
1432         txn = osp_txn_info(&th->th_ctx);
1433         if (txn == NULL || txn->oti_current_id < tr->otr_committed_id)
1434                 return;
1435
1436         spin_lock(&tr->otr_lock);
1437         if (likely(txn->oti_current_id > tr->otr_committed_id)) {
1438                 CDEBUG(D_OTHER, "committed: %u -> %u\n",
1439                        tr->otr_committed_id, txn->oti_current_id);
1440                 tr->otr_committed_id = txn->oti_current_id;
1441
1442                 list_for_each_entry(d, &tr->otr_wakeup_list,
1443                                     opd_syn_ontrack) {
1444                         d->opd_syn_last_committed_id = tr->otr_committed_id;
1445                         wake_up(&d->opd_syn_waitq);
1446                 }
1447         }
1448         spin_unlock(&tr->otr_lock);
1449 }
1450
1451 /**
1452  * Initialize commit tracking mechanism.
1453  *
1454  * Some setups may have thousands of OSTs and each will be represented by OSP.
1455  * Meaning order of magnitute many more changes to apply every second. In order
1456  * to keep the number of commit callbacks low this mechanism was introduced.
1457  * The mechanism is very similar to transno used by MDT service: it's an single
1458  * ID stream which can be assigned by any OSP to its llog records. The tricky
1459  * part is that ID is stored in per-transaction data and re-used by all the OSPs
1460  * involved in that transaction. Then all these OSPs are woken up utilizing a single OSD commit callback.
1461  *
1462  * The function initializes the data used by the tracker described above.
1463  * A singler tracker per OSD device is created.
1464  *
1465  * \param[in] d         OSP device
1466  *
1467  * \retval 0            on success
1468  * \retval negative     negated errno on error
1469  */
1470 static int osp_sync_id_traction_init(struct osp_device *d)
1471 {
1472         struct osp_id_tracker   *tr, *found = NULL;
1473         int                      rc = 0;
1474
1475         LASSERT(d);
1476         LASSERT(d->opd_storage);
1477         LASSERT(d->opd_syn_tracker == NULL);
1478         INIT_LIST_HEAD(&d->opd_syn_ontrack);
1479
1480         mutex_lock(&osp_id_tracker_sem);
1481         list_for_each_entry(tr, &osp_id_tracker_list, otr_list) {
1482                 if (tr->otr_dev == d->opd_storage) {
1483                         LASSERT(atomic_read(&tr->otr_refcount));
1484                         atomic_inc(&tr->otr_refcount);
1485                         d->opd_syn_tracker = tr;
1486                         found = tr;
1487                         break;
1488                 }
1489         }
1490
1491         if (found == NULL) {
1492                 rc = -ENOMEM;
1493                 OBD_ALLOC_PTR(tr);
1494                 if (tr) {
1495                         d->opd_syn_tracker = tr;
1496                         spin_lock_init(&tr->otr_lock);
1497                         tr->otr_dev = d->opd_storage;
1498                         tr->otr_next_id = 1;
1499                         tr->otr_committed_id = 0;
1500                         atomic_set(&tr->otr_refcount, 1);
1501                         INIT_LIST_HEAD(&tr->otr_wakeup_list);
1502                         list_add(&tr->otr_list, &osp_id_tracker_list);
1503                         tr->otr_tx_cb.dtc_txn_commit =
1504                                                 osp_sync_tracker_commit_cb;
1505                         tr->otr_tx_cb.dtc_cookie = tr;
1506                         tr->otr_tx_cb.dtc_tag = LCT_MD_THREAD;
1507                         dt_txn_callback_add(d->opd_storage, &tr->otr_tx_cb);
1508                         rc = 0;
1509                 }
1510         }
1511         mutex_unlock(&osp_id_tracker_sem);
1512
1513         return rc;
1514 }
1515
1516 /**
1517  * Release commit tracker.
1518  *
1519  * Decrease a refcounter on the tracker used by the given OSP device \a d.
1520  * If no more users left, then the tracker is released.
1521  *
1522  * \param[in] d         OSP device
1523  */
1524 static void osp_sync_id_traction_fini(struct osp_device *d)
1525 {
1526         struct osp_id_tracker *tr;
1527
1528         ENTRY;
1529
1530         LASSERT(d);
1531         tr = d->opd_syn_tracker;
1532         if (tr == NULL) {
1533                 EXIT;
1534                 return;
1535         }
1536
1537         osp_sync_remove_from_tracker(d);
1538
1539         mutex_lock(&osp_id_tracker_sem);
1540         if (atomic_dec_and_test(&tr->otr_refcount)) {
1541                 dt_txn_callback_del(d->opd_storage, &tr->otr_tx_cb);
1542                 LASSERT(list_empty(&tr->otr_wakeup_list));
1543                 list_del(&tr->otr_list);
1544                 OBD_FREE_PTR(tr);
1545                 d->opd_syn_tracker = NULL;
1546         }
1547         mutex_unlock(&osp_id_tracker_sem);
1548
1549         EXIT;
1550 }
1551
1552 /**
1553  * Generate a new ID on a tracker.
1554  *
1555  * Generates a new ID using the tracker associated with the given OSP device
1556  * \a d, if the given ID \a id is non-zero. Unconditially adds OSP device to
1557  * the wakeup list, so OSP won't miss when a transaction using the ID is
1558  * committed. Notice ID is 32bit, but llog doesn't support >2^32 records anyway.
1559  *
1560  * \param[in] d         OSP device
1561  * \param[in] id        0 or ID generated previously
1562  *
1563  * \retval              ID the caller should use
1564  */
1565 static __u32 osp_sync_id_get(struct osp_device *d, __u32 id)
1566 {
1567         struct osp_id_tracker *tr;
1568
1569         tr = d->opd_syn_tracker;
1570         LASSERT(tr);
1571
1572         /* XXX: we can improve this introducing per-cpu preallocated ids? */
1573         spin_lock(&tr->otr_lock);
1574         if (unlikely(tr->otr_next_id <= d->opd_syn_last_used_id)) {
1575                 spin_unlock(&tr->otr_lock);
1576                 CERROR("%s: next %u, last synced %lu\n",
1577                        d->opd_obd->obd_name, tr->otr_next_id,
1578                        d->opd_syn_last_used_id);
1579                 LBUG();
1580         }
1581
1582         if (id == 0)
1583                 id = tr->otr_next_id++;
1584         if (id > d->opd_syn_last_used_id)
1585                 d->opd_syn_last_used_id = id;
1586         if (list_empty(&d->opd_syn_ontrack))
1587                 list_add(&d->opd_syn_ontrack, &tr->otr_wakeup_list);
1588         spin_unlock(&tr->otr_lock);
1589         CDEBUG(D_OTHER, "new id %u\n", (unsigned) id);
1590
1591         return id;
1592 }
1593
1594 /**
1595  * Stop to propagate commit status to OSP.
1596  *
1597  * If the OSP does not have any llog records she's waiting to commit, then
1598  * it is possible to unsubscribe from wakeups from the tracking using this
1599  * method.
1600  *
1601  * \param[in] d         OSP device not willing to wakeup
1602  */
1603 static void osp_sync_remove_from_tracker(struct osp_device *d)
1604 {
1605         struct osp_id_tracker *tr;
1606
1607         tr = d->opd_syn_tracker;
1608         LASSERT(tr);
1609
1610         if (list_empty(&d->opd_syn_ontrack))
1611                 return;
1612
1613         spin_lock(&tr->otr_lock);
1614         list_del_init(&d->opd_syn_ontrack);
1615         spin_unlock(&tr->otr_lock);
1616 }
1617