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