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