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