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