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