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