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