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