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