Whamcloud - gitweb
LU-14487 modules: remove references to Sun Trademark.
[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;
765         }
766
767         osp_sync_send_new_rpc(d, llh, h, req);
768         RETURN(0);
769 }
770
771 /**
772  * Generate a request for unlink change.
773  *
774  * The function prepares a new RPC, initializes it with unlink(destroy)
775  * specific bits and sends the RPC. The function is used to handle
776  * llog_unlink_rec which were used in the older versions of Lustre.
777  * Current version uses llog_unlink_rec64.
778  *
779  * \param[in] d         OSP device
780  * \param[in] llh       llog handle where the record is stored
781  * \param[in] h         llog record
782  *
783  * \retval 0            on success
784  * \retval negative     negated errno on error
785  */
786 static int osp_sync_new_unlink_job(struct osp_device *d,
787                                    struct llog_handle *llh,
788                                    struct llog_rec_hdr *h)
789 {
790         struct llog_unlink_rec  *rec = (struct llog_unlink_rec *)h;
791         struct ptlrpc_request   *req;
792         struct ost_body         *body;
793         int rc;
794
795         ENTRY;
796         LASSERT(h->lrh_type == MDS_UNLINK_REC);
797
798         req = osp_sync_new_job(d, OST_DESTROY, &RQF_OST_DESTROY);
799         if (IS_ERR(req))
800                 RETURN(PTR_ERR(req));
801
802         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
803         LASSERT(body);
804         ostid_set_seq(&body->oa.o_oi, rec->lur_oseq);
805         rc = ostid_set_id(&body->oa.o_oi, rec->lur_oid);
806         if (rc)
807                 return rc;
808         body->oa.o_misc = rec->lur_count;
809         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID;
810         if (rec->lur_count)
811                 body->oa.o_valid |= OBD_MD_FLOBJCOUNT;
812
813         osp_sync_send_new_rpc(d, llh, h, req);
814         RETURN(0);
815 }
816
817 /**
818  * Generate a request for unlink change.
819  *
820  * The function prepares a new RPC, initializes it with unlink(destroy)
821  * specific bits and sends the RPC. Depending on the target (MDT or OST)
822  * two different protocols are used. For MDT we use OUT (basically OSD API
823  * updates transferred via a network). For OST we still use the old
824  * protocol (OBD?), originally for compatibility. Later we can start to
825  * use OUT for OST as well, this will allow batching and better code
826  * unification.
827  *
828  * \param[in] d         OSP device
829  * \param[in] llh       llog handle where the record is stored
830  * \param[in] h         llog record
831  *
832  * \retval 0            on success
833  * \retval negative     negated errno on error
834  */
835 static int osp_sync_new_unlink64_job(struct osp_device *d,
836                                      struct llog_handle *llh,
837                                      struct llog_rec_hdr *h)
838 {
839         struct llog_unlink64_rec        *rec = (struct llog_unlink64_rec *)h;
840         struct ptlrpc_request           *req = NULL;
841         struct ost_body                 *body;
842         int                              rc;
843
844         ENTRY;
845         LASSERT(h->lrh_type == MDS_UNLINK64_REC);
846         req = osp_sync_new_job(d, OST_DESTROY, &RQF_OST_DESTROY);
847         if (IS_ERR(req))
848                 RETURN(PTR_ERR(req));
849
850         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
851         if (body == NULL)
852                 RETURN(-EFAULT);
853         rc = fid_to_ostid(&rec->lur_fid, &body->oa.o_oi);
854         if (rc < 0)
855                 RETURN(rc);
856         body->oa.o_misc = rec->lur_count;
857         body->oa.o_valid = OBD_MD_FLGROUP | OBD_MD_FLID |
858                            OBD_MD_FLOBJCOUNT;
859         osp_sync_send_new_rpc(d, llh, h, req);
860         RETURN(0);
861 }
862
863 /**
864  * Process llog records.
865  *
866  * This function is called to process the llog records committed locally.
867  * In the recovery model used by OSP we can apply a change to a remote
868  * target once corresponding transaction (like posix unlink) is committed
869  * locally so can't revert.
870  * Depending on the llog record type, a given handler is called that is
871  * responsible for preparing and sending the RPC to apply the change.
872  * Special record type LLOG_GEN_REC marking a reboot is cancelled right away.
873  *
874  * \param[in] env       LU environment provided by the caller
875  * \param[in] d         OSP device
876  * \param[in] llh       llog handle where the record is stored
877  * \param[in] rec       llog record
878  */
879 static void osp_sync_process_record(const struct lu_env *env,
880                                     struct osp_device *d,
881                                     struct llog_handle *llh,
882                                     struct llog_rec_hdr *rec)
883 {
884         struct llog_handle      *cathandle = llh->u.phd.phd_cat_handle;
885         struct llog_cookie       cookie;
886         int                      rc = 0;
887
888         ENTRY;
889
890         cookie.lgc_lgl = llh->lgh_id;
891         cookie.lgc_subsys = LLOG_MDS_OST_ORIG_CTXT;
892         cookie.lgc_index = rec->lrh_index;
893
894         d->opd_sync_last_catalog_idx = llh->lgh_hdr->llh_cat_idx;
895
896         if (unlikely(rec->lrh_type == LLOG_GEN_REC)) {
897                 struct llog_gen_rec *gen = (struct llog_gen_rec *)rec;
898
899                 /* we're waiting for the record generated by this instance */
900                 LASSERT(d->opd_sync_prev_done == 0);
901                 if (!memcmp(&d->opd_sync_generation, &gen->lgr_gen,
902                             sizeof(gen->lgr_gen))) {
903                         CDEBUG(D_HA, "processed all old entries\n");
904                         d->opd_sync_prev_done = 1;
905                 }
906
907                 /* cancel any generation record */
908                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
909
910                 /* flush all pending records ASAP */
911                 osp_sync_force(env, d);
912
913                 RETURN_EXIT;
914         }
915
916         /*
917          * now we prepare and fill requests to OST, put them on the queue
918          * and fire after next commit callback
919          */
920
921         /* notice we increment counters before sending RPC, to be consistent
922          * in RPC interpret callback which may happen very quickly */
923         atomic_inc(&d->opd_sync_rpcs_in_flight);
924         atomic_inc(&d->opd_sync_rpcs_in_progress);
925
926         switch (rec->lrh_type) {
927         /* case MDS_UNLINK_REC is kept for compatibility */
928         case MDS_UNLINK_REC:
929                 rc = osp_sync_new_unlink_job(d, llh, rec);
930                 break;
931         case MDS_UNLINK64_REC:
932                 rc = osp_sync_new_unlink64_job(d, llh, rec);
933                 break;
934         case MDS_SETATTR64_REC:
935                 rc = osp_sync_new_setattr_job(d, llh, rec);
936                 break;
937         default:
938                 CERROR("%s: unknown record type: %x\n", d->opd_obd->obd_name,
939                        rec->lrh_type);
940                 /* treat "unknown record type" as "invalid" */
941                 rc = 1;
942                 break;
943         }
944
945         /* For all kinds of records, not matter successful or not,
946          * we should decrease changes and bump last_processed_id.
947          */
948         if (d->opd_sync_prev_done) {
949                 LASSERT(atomic_read(&d->opd_sync_changes) > 0);
950                 atomic_dec(&d->opd_sync_changes);
951                 wake_up(&d->opd_sync_barrier_waitq);
952         }
953         atomic64_inc(&d->opd_sync_processed_recs);
954         if (rc != 0) {
955                 atomic_dec(&d->opd_sync_rpcs_in_flight);
956                 atomic_dec(&d->opd_sync_rpcs_in_progress);
957         }
958
959         CDEBUG(D_OTHER, "%s: %d in flight, %d in progress\n",
960                d->opd_obd->obd_name, atomic_read(&d->opd_sync_rpcs_in_flight),
961                atomic_read(&d->opd_sync_rpcs_in_progress));
962
963         /* Delete the invalid record */
964         if (rc == 1) {
965                 rc = llog_cat_cancel_records(env, cathandle, 1, &cookie);
966                 if (rc != 0)
967                         CERROR("%s: can't delete invalid record: "
968                                "fid = "DFID", rec_id = %u, rc = %d\n",
969                                d->opd_obd->obd_name,
970                                PFID(lu_object_fid(&cathandle->lgh_obj->do_lu)),
971                                rec->lrh_id, rc);
972         }
973
974         CDEBUG(D_OTHER, "found record %x, %d, idx %u, id %u\n",
975                rec->lrh_type, rec->lrh_len, rec->lrh_index, rec->lrh_id);
976
977         RETURN_EXIT;
978 }
979
980 /**
981  * Cancel llog records for the committed changes.
982  *
983  * The function walks through the list of the committed RPCs and cancels
984  * corresponding llog records. see osp_sync_request_commit_cb() for the
985  * details.
986  *
987  * \param[in] env       LU environment provided by the caller
988  * \param[in] d         OSP device
989  */
990 static void osp_sync_process_committed(const struct lu_env *env,
991                                        struct osp_device *d)
992 {
993         struct obd_device       *obd = d->opd_obd;
994         struct obd_import       *imp = obd->u.cli.cl_import;
995         struct ost_body         *body;
996         struct ptlrpc_request   *req;
997         struct llog_ctxt        *ctxt;
998         struct llog_handle      *llh;
999         int                     *arr;
1000         LIST_HEAD(list);
1001         struct list_head         *le;
1002         struct llog_logid        lgid;
1003         int                      rc, i, count = 0, done = 0;
1004
1005         ENTRY;
1006
1007         if (list_empty(&d->opd_sync_committed_there))
1008                 return;
1009
1010         /*
1011          * if current status is -ENOSPC (lack of free space on OST)
1012          * then we should poll OST immediately once object destroy
1013          * is committed.
1014          * notice: we do this upon commit as well because some backends
1015          * (like DMU) do not release space right away.
1016          */
1017         if (d->opd_pre != NULL && unlikely(d->opd_pre_status == -ENOSPC))
1018                 osp_statfs_need_now(d);
1019
1020         /*
1021          * now cancel them all
1022          * XXX: can we improve this using some batching?
1023          *      with batch RPC that'll happen automatically?
1024          * XXX: can we store ctxt in lod_device and save few cycles ?
1025          */
1026         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1027         LASSERT(ctxt);
1028
1029         llh = ctxt->loc_handle;
1030         LASSERT(llh);
1031
1032         spin_lock(&d->opd_sync_lock);
1033         list_splice(&d->opd_sync_committed_there, &list);
1034         INIT_LIST_HEAD(&d->opd_sync_committed_there);
1035         spin_unlock(&d->opd_sync_lock);
1036
1037         list_for_each(le, &list)
1038                 count++;
1039         if (count > 2)
1040                 OBD_ALLOC_PTR_ARRAY_LARGE(arr, count);
1041         else
1042                 arr = NULL;
1043         i = 0;
1044         while (!list_empty(&list)) {
1045                 struct osp_job_req_args *jra;
1046
1047                 jra = list_entry(list.next, struct osp_job_req_args,
1048                                  jra_committed_link);
1049                 LASSERT(jra->jra_magic == OSP_JOB_MAGIC);
1050                 list_del_init(&jra->jra_committed_link);
1051
1052                 req = container_of((void *)jra, struct ptlrpc_request,
1053                                    rq_async_args);
1054                 body = req_capsule_client_get(&req->rq_pill,
1055                                               &RMF_OST_BODY);
1056                 LASSERT(body);
1057                 /* import can be closing, thus all commit cb's are
1058                  * called we can check committness directly */
1059                 if (req->rq_import_generation == imp->imp_generation) {
1060                         if (arr && (!i ||
1061                                     !memcmp(&jra->jra_lcookie.lgc_lgl, &lgid,
1062                                            sizeof(lgid)))) {
1063                                 if (unlikely(!i))
1064                                         lgid = jra->jra_lcookie.lgc_lgl;
1065
1066                                 arr[i++] = jra->jra_lcookie.lgc_index;
1067                         } else {
1068                                 rc = llog_cat_cancel_records(env, llh, 1,
1069                                                              &jra->jra_lcookie);
1070                                 if (rc)
1071                                         CERROR("%s: can't cancel record: %d\n",
1072                                                obd->obd_name, rc);
1073                         }
1074                 } else {
1075                         DEBUG_REQ(D_OTHER, req, "imp_committed = %llu",
1076                                   imp->imp_peer_committed_transno);
1077                 }
1078                 ptlrpc_req_finished(req);
1079                 done++;
1080         }
1081         if (arr && i > 0) {
1082                 rc = llog_cat_cancel_arr_rec(env, llh, &lgid, i, arr);
1083
1084                 if (rc)
1085                         CERROR("%s: can't cancel %d records rc: %d\n",
1086                                obd->obd_name, i, rc);
1087                 else
1088                         CDEBUG(D_OTHER, "%s: massive records cancel id "DFID\
1089                                " num %d\n", obd->obd_name,
1090                                PFID(&lgid.lgl_oi.oi_fid), i);
1091         }
1092         if (arr)
1093                 OBD_FREE_PTR_ARRAY_LARGE(arr, count);
1094
1095         llog_ctxt_put(ctxt);
1096
1097         LASSERT(atomic_read(&d->opd_sync_rpcs_in_progress) >= done);
1098         atomic_sub(done, &d->opd_sync_rpcs_in_progress);
1099         CDEBUG((done > 2 ? D_HA : D_OTHER), "%s: %u changes, %u in progress,"
1100                                      " %u in flight, %u done\n",
1101                                      d->opd_obd->obd_name,
1102                                      atomic_read(&d->opd_sync_changes),
1103                                      atomic_read(&d->opd_sync_rpcs_in_progress),
1104                                      atomic_read(&d->opd_sync_rpcs_in_flight),
1105                                      done);
1106
1107         osp_sync_check_for_work(d);
1108
1109         /* wake up the thread if requested to stop:
1110          * it might be waiting for in-progress to complete
1111          */
1112         if (atomic_read(&d->opd_sync_rpcs_in_progress) == 0)
1113                 wake_up(&d->opd_sync_waitq);
1114
1115         EXIT;
1116 }
1117
1118 /**
1119  * The core of the syncing mechanism.
1120  *
1121  * This is a callback called by the llog processing function. Essentially it
1122  * suspends llog processing until there is a record to process (it's supposed
1123  * to be committed locally). The function handles RPCs committed by the target
1124  * and cancels corresponding llog records.
1125  *
1126  * \param[in] env       LU environment provided by the caller
1127  * \param[in] llh       llog handle we're processing
1128  * \param[in] rec       current llog record
1129  * \param[in] data      callback data containing a pointer to the device
1130  *
1131  * \retval 0                    to ask the caller (llog_process()) to continue
1132  * \retval LLOG_PROC_BREAK      to ask the caller to break
1133  */
1134 static int osp_sync_process_queues(const struct lu_env *env,
1135                                    struct llog_handle *llh,
1136                                    struct llog_rec_hdr *rec,
1137                                    void *data)
1138 {
1139         struct osp_device       *d = data;
1140
1141         do {
1142                 if (!d->opd_sync_task) {
1143                         CDEBUG(D_HA, "stop llog processing\n");
1144                         return LLOG_PROC_BREAK;
1145                 }
1146
1147                 /* process requests committed by OST */
1148                 osp_sync_process_committed(env, d);
1149
1150                 /* if we there are changes to be processed and we have
1151                  * resources for this ... do now */
1152                 if (osp_sync_can_process_new(d, rec)) {
1153                         if (llh == NULL) {
1154                                 /* ask llog for another record */
1155                                 return 0;
1156                         }
1157                         osp_sync_process_record(env, d, llh, rec);
1158                         llh = NULL;
1159                         rec = NULL;
1160                 }
1161                 if (OBD_FAIL_PRECHECK(OBD_FAIL_CATALOG_FULL_CHECK) &&
1162                             cfs_fail_val != 1)
1163                         msleep(1 * MSEC_PER_SEC);
1164
1165                 wait_event_idle(d->opd_sync_waitq,
1166                                 !d->opd_sync_task ||
1167                                 osp_sync_can_process_new(d, rec) ||
1168                                 !list_empty(&d->opd_sync_committed_there));
1169         } while (1);
1170 }
1171
1172 struct osp_sync_args {
1173         struct osp_device       *osa_dev;
1174         struct lu_env            osa_env;
1175         struct completion       *osa_started;
1176 };
1177
1178 /**
1179  * OSP sync thread.
1180  *
1181  * This thread runs llog_cat_process() scanner calling our callback
1182  * to process llog records. in the callback we implement tricky
1183  * state machine as we don't want to start scanning of the llog again
1184  * and again, also we don't want to process too many records and send
1185  * too many RPCs a time. so, depending on current load (num of changes
1186  * being synced to OST) the callback can suspend awaiting for some
1187  * new conditions, like syncs completed.
1188  *
1189  * In order to process llog records left by previous boots and to allow
1190  * llog_process_thread() to find something (otherwise it'd just exit
1191  * immediately) we add a special GENERATATION record on each boot.
1192  *
1193  * \param[in] _arg      a pointer to thread's arguments
1194  *
1195  * \retval 0            on success
1196  * \retval negative     negated errno on error
1197  */
1198 static int osp_sync_thread(void *_args)
1199 {
1200         struct osp_sync_args    *args = _args;
1201         struct osp_device       *d = args->osa_dev;
1202         struct llog_ctxt        *ctxt;
1203         struct obd_device       *obd = d->opd_obd;
1204         struct llog_handle      *llh;
1205         struct lu_env           *env = &args->osa_env;
1206         int                      rc, count;
1207         bool                     wrapped;
1208
1209         ENTRY;
1210
1211         complete(args->osa_started);
1212 again:
1213         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1214         if (ctxt == NULL) {
1215                 CERROR("can't get appropriate context\n");
1216                 GOTO(out, rc = -EINVAL);
1217         }
1218
1219         llh = ctxt->loc_handle;
1220         if (llh == NULL) {
1221                 CERROR("can't get llh\n");
1222                 llog_ctxt_put(ctxt);
1223                 GOTO(out, rc = -EINVAL);
1224         }
1225
1226         /*
1227          * Catalog processing stops when it processed last catalog record
1228          * with index equal to the end of catalog bitmap. Or if it is wrapped,
1229          * processing stops with index equal to the lgh_last_idx. We need to
1230          * continue processing.
1231          */
1232         d->opd_sync_last_catalog_idx = 0;
1233         do {
1234                 int     size;
1235
1236                 wrapped = (llh->lgh_hdr->llh_cat_idx >= llh->lgh_last_idx &&
1237                            llh->lgh_hdr->llh_count > 1);
1238
1239                 if (OBD_FAIL_CHECK(OBD_FAIL_OSP_CANT_PROCESS_LLOG)) {
1240                         rc = -EINPROGRESS;
1241                         goto next;
1242                 }
1243                 rc = llog_cat_process(env, llh, osp_sync_process_queues, d,
1244                                       d->opd_sync_last_catalog_idx, 0);
1245
1246 next:
1247                 size = OBD_FAIL_PRECHECK(OBD_FAIL_CAT_RECORDS) ?
1248                        cfs_fail_val : (LLOG_HDR_BITMAP_SIZE(llh->lgh_hdr) - 1);
1249                 /* processing reaches catalog bottom */
1250                 if (d->opd_sync_last_catalog_idx == size)
1251                         d->opd_sync_last_catalog_idx = LLOG_CAT_FIRST;
1252                 /* If catalog is wrapped we can`t predict last index of
1253                  * processing because lgh_last_idx could be changed.
1254                  * Starting form the next one. Index would be increased
1255                  * at llog_process_thread
1256                  */
1257         } while (rc == 0 && (wrapped ||
1258                              d->opd_sync_last_catalog_idx == LLOG_CAT_FIRST));
1259
1260         if (rc < 0) {
1261                 if (rc == -EINPROGRESS) {
1262                         /* can't access the llog now - OI scrub is trying to fix
1263                          * underlying issue. let's wait and try again */
1264                         llog_cat_close(env, llh);
1265                         rc = llog_cleanup(env, ctxt);
1266                         if (rc)
1267                                 GOTO(out, rc);
1268                         schedule_timeout_interruptible(cfs_time_seconds(5));
1269                         goto again;
1270                 }
1271
1272                 CERROR("%s: llog process with osp_sync_process_queues "
1273                        "failed: %d\n", d->opd_obd->obd_name, rc);
1274                 GOTO(wait, rc);
1275         }
1276         LASSERTF(rc == 0 || rc == LLOG_PROC_BREAK,
1277                  "%u changes, %u in progress, %u in flight: %d\n",
1278                  atomic_read(&d->opd_sync_changes),
1279                  atomic_read(&d->opd_sync_rpcs_in_progress),
1280                  atomic_read(&d->opd_sync_rpcs_in_flight), rc);
1281
1282         /* we don't expect llog_process_thread() to exit till umount */
1283         LASSERTF(kthread_should_stop(),
1284                  "%u changes, %u in progress, %u in flight\n",
1285                  atomic_read(&d->opd_sync_changes),
1286                  atomic_read(&d->opd_sync_rpcs_in_progress),
1287                  atomic_read(&d->opd_sync_rpcs_in_flight));
1288
1289 wait:
1290         /* wait till all the requests are completed */
1291         count = 0;
1292         while (atomic_read(&d->opd_sync_rpcs_in_progress) > 0) {
1293                 osp_sync_process_committed(env, d);
1294
1295                 rc = wait_event_idle_timeout(
1296                         d->opd_sync_waitq,
1297                         atomic_read(&d->opd_sync_rpcs_in_progress) == 0,
1298                         cfs_time_seconds(5));
1299                 if (rc == 0)
1300                         count++;
1301                 LASSERTF(count < 10, "%s: %d %d %sempty\n",
1302                          d->opd_obd->obd_name,
1303                          atomic_read(&d->opd_sync_rpcs_in_progress),
1304                          atomic_read(&d->opd_sync_rpcs_in_flight),
1305                          list_empty(&d->opd_sync_committed_there) ? "" : "!");
1306
1307         }
1308
1309         llog_cat_close(env, llh);
1310         rc = llog_cleanup(env, ctxt);
1311         if (rc)
1312                 CERROR("can't cleanup llog: %d\n", rc);
1313 out:
1314         LASSERTF(atomic_read(&d->opd_sync_rpcs_in_progress) == 0,
1315                  "%s: %d %d %sempty\n", d->opd_obd->obd_name,
1316                  atomic_read(&d->opd_sync_rpcs_in_progress),
1317                  atomic_read(&d->opd_sync_rpcs_in_flight),
1318                  list_empty(&d->opd_sync_committed_there) ? "" : "!");
1319
1320         lu_env_fini(env);
1321
1322         if (xchg(&d->opd_sync_task, NULL) == NULL)
1323                 /* already being waited for */
1324                 wait_event_interruptible(d->opd_sync_waitq,
1325                                          kthread_should_stop());
1326         OBD_FREE_PTR(args);
1327
1328         RETURN(0);
1329 }
1330
1331 /**
1332  * Initialize llog.
1333  *
1334  * Initializes the llog. Specific llog to be used depends on the type of the
1335  * target OSP represents (OST or MDT). The function adds appends a new llog
1336  * record to mark the place where the records associated with this boot
1337  * start.
1338  *
1339  * \param[in] env       LU environment provided by the caller
1340  * \param[in] d         OSP device
1341  *
1342  * \retval 0            on success
1343  * \retval negative     negated errno on error
1344  */
1345 static int osp_sync_llog_init(const struct lu_env *env, struct osp_device *d)
1346 {
1347         struct osp_thread_info  *osi = osp_env_info(env);
1348         struct lu_fid           *fid = &osi->osi_fid;
1349         struct llog_handle      *lgh = NULL;
1350         struct obd_device       *obd = d->opd_obd;
1351         struct llog_ctxt        *ctxt;
1352         int                     rc;
1353
1354         ENTRY;
1355
1356         LASSERT(obd);
1357
1358         /*
1359          * open llog corresponding to our OST
1360          */
1361         OBD_SET_CTXT_MAGIC(&obd->obd_lvfs_ctxt);
1362         obd->obd_lvfs_ctxt.dt = d->opd_storage;
1363
1364         lu_local_obj_fid(fid, LLOG_CATALOGS_OID);
1365
1366         rc = llog_osd_get_cat_list(env, d->opd_storage, d->opd_index, 1,
1367                                    &osi->osi_cid, fid);
1368         if (rc < 0) {
1369                 if (rc != -EFAULT) {
1370                         CERROR("%s: can't get id from catalogs: rc = %d\n",
1371                                obd->obd_name, rc);
1372                         RETURN(rc);
1373                 }
1374
1375                 /* After sparse OST indices is supported, the CATALOG file
1376                  * may become a sparse file that results in failure on
1377                  * reading. Skip this error as the llog will be created
1378                  * later */
1379                 memset(&osi->osi_cid, 0, sizeof(osi->osi_cid));
1380                 rc = 0;
1381         }
1382
1383         CDEBUG(D_INFO, "%s: Init llog for %d - catid "DFID":%x\n",
1384                obd->obd_name, d->opd_index,
1385                PFID(&osi->osi_cid.lci_logid.lgl_oi.oi_fid),
1386                osi->osi_cid.lci_logid.lgl_ogen);
1387
1388         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_MDS_OST_ORIG_CTXT,
1389                         d->opd_storage->dd_lu_dev.ld_obd,
1390                         &llog_common_cat_ops);
1391         if (rc)
1392                 RETURN(rc);
1393
1394         ctxt = llog_get_context(obd, LLOG_MDS_OST_ORIG_CTXT);
1395         LASSERT(ctxt);
1396
1397         if (likely(logid_id(&osi->osi_cid.lci_logid) != 0)) {
1398                 struct lu_fid fid_temp;
1399
1400                 if (CFS_FAIL_CHECK(OBD_FAIL_OSP_INVALID_LOGID)) {
1401                         memset(&osi->osi_cid, 0, sizeof(osi->osi_cid));
1402                         logid_set_id(&osi->osi_cid.lci_logid, cfs_fail_val);
1403                 }
1404
1405                 logid_to_fid(&osi->osi_cid.lci_logid, &fid_temp);
1406                 if (fid_is_sane(&fid_temp)) {
1407                         rc = llog_open(env, ctxt, &lgh, &osi->osi_cid.lci_logid,
1408                                        NULL, LLOG_OPEN_EXISTS);
1409
1410                         /* re-create llog if it is missing */
1411                         if (rc == -ENOENT)
1412                                 logid_set_id(&osi->osi_cid.lci_logid, 0);
1413                         else if (rc < 0)
1414                                 GOTO(out_cleanup, rc);
1415                 } else {
1416                         CERROR("%s: the catid "DFID" for init llog %d is bad\n",
1417                                obd->obd_name, PFID(&fid_temp), d->opd_index);
1418
1419                         /* it will be recreated later */
1420                         logid_set_id(&osi->osi_cid.lci_logid, 0);
1421                 }
1422         }
1423
1424         if (unlikely(logid_id(&osi->osi_cid.lci_logid) == 0)) {
1425                 rc = llog_open_create(env, ctxt, &lgh, NULL, NULL);
1426                 if (rc < 0)
1427                         GOTO(out_cleanup, rc);
1428                 osi->osi_cid.lci_logid = lgh->lgh_id;
1429         }
1430
1431         LASSERT(lgh != NULL);
1432         ctxt->loc_handle = lgh;
1433
1434         rc = llog_init_handle(env, lgh, LLOG_F_IS_CAT | LLOG_F_RM_ON_ERR, NULL);
1435         if (rc)
1436                 GOTO(out_close, rc);
1437
1438         rc = llog_osd_put_cat_list(env, d->opd_storage, d->opd_index, 1,
1439                                    &osi->osi_cid, fid);
1440         if (rc)
1441                 GOTO(out_close, rc);
1442
1443         /*
1444          * put a mark in the llog till which we'll be processing
1445          * old records restless
1446          */
1447         d->opd_sync_generation.mnt_cnt = ktime_get_ns();
1448         d->opd_sync_generation.conn_cnt = ktime_get_ns();
1449
1450         osi->osi_hdr.lrh_type = LLOG_GEN_REC;
1451         osi->osi_hdr.lrh_len = sizeof(osi->osi_gen);
1452
1453         memcpy(&osi->osi_gen.lgr_gen, &d->opd_sync_generation,
1454                sizeof(osi->osi_gen.lgr_gen));
1455
1456         rc = llog_cat_add(env, lgh, &osi->osi_gen.lgr_hdr, &osi->osi_cookie);
1457         if (rc < 0)
1458                 GOTO(out_close, rc);
1459         llog_ctxt_put(ctxt);
1460         RETURN(0);
1461 out_close:
1462         llog_cat_close(env, lgh);
1463 out_cleanup:
1464         llog_cleanup(env, ctxt);
1465         RETURN(rc);
1466 }
1467
1468 /**
1469  * Cleanup llog used for syncing.
1470  *
1471  * Closes and cleanups the llog. The function is called when the device is
1472  * shutting down.
1473  *
1474  * \param[in] env       LU environment provided by the caller
1475  * \param[in] d         OSP device
1476  */
1477 static void osp_sync_llog_fini(const struct lu_env *env, struct osp_device *d)
1478 {
1479         struct llog_ctxt *ctxt;
1480
1481         ctxt = llog_get_context(d->opd_obd, LLOG_MDS_OST_ORIG_CTXT);
1482         if (ctxt) {
1483                 llog_cat_close(env, ctxt->loc_handle);
1484                 llog_cleanup(env, ctxt);
1485         }
1486 }
1487
1488 /**
1489  * Initialization of the sync component of OSP.
1490  *
1491  * Initializes the llog and starts a new thread to handle the changes to
1492  * the remote target (OST or MDT).
1493  *
1494  * \param[in] env       LU environment provided by the caller
1495  * \param[in] d         OSP device
1496  *
1497  * \retval 0            on success
1498  * \retval negative     negated errno on error
1499  */
1500 int osp_sync_init(const struct lu_env *env, struct osp_device *d)
1501 {
1502         struct task_struct      *task;
1503         struct osp_sync_args    *args;
1504         DECLARE_COMPLETION_ONSTACK(started);
1505         int                      rc;
1506
1507         ENTRY;
1508
1509         d->opd_sync_max_rpcs_in_flight = OSP_MAX_RPCS_IN_FLIGHT;
1510         d->opd_sync_max_rpcs_in_progress = OSP_MAX_RPCS_IN_PROGRESS;
1511         spin_lock_init(&d->opd_sync_lock);
1512         init_waitqueue_head(&d->opd_sync_waitq);
1513         init_waitqueue_head(&d->opd_sync_barrier_waitq);
1514         INIT_LIST_HEAD(&d->opd_sync_in_flight_list);
1515         INIT_LIST_HEAD(&d->opd_sync_committed_there);
1516
1517         if (d->opd_storage->dd_rdonly)
1518                 RETURN(0);
1519
1520         OBD_ALLOC_PTR(args);
1521         if (!args)
1522                 GOTO(err_id, rc = -ENOMEM);
1523         args->osa_dev = d;
1524         args->osa_started = &started;
1525         /*
1526          * initialize llog storing changes
1527          */
1528         rc = osp_sync_llog_init(env, d);
1529         if (rc) {
1530                 CERROR("%s: can't initialize llog: rc = %d\n",
1531                        d->opd_obd->obd_name, rc);
1532                 GOTO(err_id, rc);
1533         }
1534
1535         rc = lu_env_init(&args->osa_env, LCT_LOCAL);
1536         if (rc) {
1537                 CERROR("%s: can't initialize env: rc = %d\n",
1538                        d->opd_obd->obd_name, rc);
1539                 GOTO(err_llog, rc);
1540         }
1541
1542         /*
1543          * Start synchronization thread
1544          */
1545         task = kthread_create(osp_sync_thread, args, "osp-syn-%u-%u",
1546                            d->opd_index, d->opd_group);
1547         if (IS_ERR(task)) {
1548                 rc = PTR_ERR(task);
1549                 CERROR("%s: cannot start sync thread: rc = %d\n",
1550                        d->opd_obd->obd_name, rc);
1551                 lu_env_fini(&args->osa_env);
1552                 GOTO(err_llog, rc);
1553         }
1554         d->opd_sync_task = task;
1555         wake_up_process(task);
1556         wait_for_completion(&started);
1557
1558         RETURN(0);
1559 err_llog:
1560         osp_sync_llog_fini(env, d);
1561 err_id:
1562         if (args)
1563                 OBD_FREE_PTR(args);
1564         return rc;
1565 }
1566
1567 /**
1568  * Stop the syncing thread.
1569  *
1570  * Asks the syncing thread to stop and wait until it's stopped.
1571  *
1572  * \param[in] d         OSP device
1573  *
1574  * \retval              0
1575  */
1576 int osp_sync_fini(struct osp_device *d)
1577 {
1578         struct task_struct *task;
1579
1580         ENTRY;
1581
1582         task = xchg(&d->opd_sync_task, NULL);
1583         if (task)
1584                 kthread_stop(task);
1585
1586         RETURN(0);
1587 }
1588
1589 struct osp_last_committed_cb {
1590         struct dt_txn_commit_cb  ospc_cb;
1591         struct osp_device       *ospc_dev;
1592         __u64                    ospc_transno;
1593 };
1594
1595 void osp_sync_local_commit_cb(struct lu_env *env, struct thandle *th,
1596                               struct dt_txn_commit_cb *dcb, int err)
1597 {
1598         struct osp_last_committed_cb    *cb;
1599         struct osp_device               *d;
1600
1601         cb = container_of(dcb, struct osp_last_committed_cb, ospc_cb);
1602         d = cb->ospc_dev;
1603
1604         CDEBUG(D_HA, "%s: %llu committed\n", d->opd_obd->obd_name,
1605                cb->ospc_transno);
1606
1607         spin_lock(&d->opd_sync_lock);
1608         if (cb->ospc_transno > d->opd_sync_last_committed_id)
1609                 d->opd_sync_last_committed_id = cb->ospc_transno;
1610         spin_unlock(&d->opd_sync_lock);
1611
1612         osp_sync_check_for_work(d);
1613         lu_device_put(osp2lu_dev(d));
1614         if (atomic_dec_and_test(&d->opd_commits_registered))
1615                 wake_up(&d->opd_sync_waitq);
1616
1617         OBD_FREE_PTR(cb);
1618 }
1619
1620 static int osp_sync_add_commit_cb(const struct lu_env *env,
1621                                   struct osp_device *d, struct thandle *th)
1622 {
1623         struct osp_last_committed_cb    *cb;
1624         struct dt_txn_commit_cb         *dcb;
1625         int                              rc = 0;
1626
1627         OBD_ALLOC_PTR(cb);
1628         if (cb == NULL)
1629                 return -ENOMEM;
1630         cb->ospc_dev = d;
1631         dcb = &cb->ospc_cb;
1632         dcb->dcb_func = osp_sync_local_commit_cb;
1633         spin_lock(&d->opd_sync_lock);
1634         cb->ospc_transno = ++d->opd_sync_last_used_id;
1635         spin_unlock(&d->opd_sync_lock);
1636
1637         rc = dt_trans_cb_add(th, dcb);
1638         CDEBUG(D_HA, "%s: add commit cb at %lluns, next at %lluns, rc = %d\n",
1639                d->opd_obd->obd_name, ktime_get_ns(),
1640                ktime_to_ns(d->opd_sync_next_commit_cb), rc);
1641
1642         if (likely(rc == 0)) {
1643                 lu_device_get(osp2lu_dev(d));
1644                 atomic_inc(&d->opd_commits_registered);
1645         } else
1646                 OBD_FREE_PTR(cb);
1647
1648         return rc;
1649 }
1650
1651 /* add the commit callback every second */
1652 int osp_sync_add_commit_cb_1s(const struct lu_env *env, struct osp_device *d,
1653                               struct thandle *th)
1654 {
1655         ktime_t now = ktime_get();
1656         bool add = false;
1657
1658         /* fast path */
1659         if (ktime_before(now, d->opd_sync_next_commit_cb))
1660                 return 0;
1661
1662         spin_lock(&d->opd_sync_lock);
1663         if (ktime_before(d->opd_sync_next_commit_cb, now)) {
1664                 add = true;
1665                 d->opd_sync_next_commit_cb = ktime_add_ns(now, NSEC_PER_SEC);
1666         }
1667         spin_unlock(&d->opd_sync_lock);
1668
1669         if (!add)
1670                 return 0;
1671
1672         return osp_sync_add_commit_cb(env, d, th);
1673 }
1674
1675 /*
1676  * generate an empty transaction and hook the commit callback in
1677  * then force transaction commit
1678  */
1679 void osp_sync_force(const struct lu_env *env, struct osp_device *d)
1680 {
1681         struct thandle *th;
1682         int rc;
1683
1684         th = dt_trans_create(env, d->opd_storage);
1685         if (IS_ERR(th)) {
1686                 CERROR("%s: can't sync\n", d->opd_obd->obd_name);
1687                 return;
1688         }
1689         rc = dt_trans_start_local(env, d->opd_storage, th);
1690         if (rc == 0) {
1691                 CDEBUG(D_OTHER, "%s: sync forced, %d changes\n",
1692                        d->opd_obd->obd_name,
1693                        atomic_read(&d->opd_sync_changes));
1694                 rc = osp_sync_add_commit_cb(env, d, th);
1695                 dt_trans_stop(env, d->opd_storage, th);
1696         }
1697
1698         dt_commit_async(env, d->opd_storage);
1699 }