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