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