Whamcloud - gitweb
LU-6401 uapi: fix up lustre_ostid.h and lustre_fid.h
[fs/lustre-release.git] / lustre / osp / osp_precreate.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, 2016, 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  * Author: Di Wang <di.wang@intel.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_MDS
42
43 #include <linux/kthread.h>
44
45 #include <lustre_obdo.h>
46
47 #include "osp_internal.h"
48
49 /*
50  * there are two specific states to take care about:
51  *
52  * = import is disconnected =
53  *
54  * = import is inactive =
55  *   in this case osp_declare_object_create() returns an error
56  *
57  */
58
59 /*
60  **
61  * Check whether statfs data is expired
62  *
63  * OSP device caches statfs data for the target, the function checks
64  * whether the data is expired or not.
65  *
66  * \param[in] d         OSP device
67  *
68  * \retval              0 - not expired, 1 - expired
69  */
70 static inline int osp_statfs_need_update(struct osp_device *d)
71 {
72         return !cfs_time_before(cfs_time_current(),
73                                 d->opd_statfs_fresh_till);
74 }
75
76 /*
77  * OSP tries to maintain pool of available objects so that calls to create
78  * objects don't block most of time
79  *
80  * each time OSP gets connected to OST, we should start from precreation cleanup
81  */
82 static inline bool osp_precreate_running(struct osp_device *d)
83 {
84         return !!(d->opd_pre_thread.t_flags & SVC_RUNNING);
85 }
86
87 static inline bool osp_precreate_stopped(struct osp_device *d)
88 {
89         return !!(d->opd_pre_thread.t_flags & SVC_STOPPED);
90 }
91
92 static void osp_statfs_timer_cb(unsigned long _d)
93 {
94         struct osp_device *d = (struct osp_device *) _d;
95
96         LASSERT(d);
97         if (d->opd_pre != NULL && osp_precreate_running(d))
98                 wake_up(&d->opd_pre_waitq);
99 }
100
101 /**
102  * RPC interpret callback for OST_STATFS RPC
103  *
104  * An interpretation callback called by ptlrpc for OST_STATFS RPC when it is
105  * replied by the target. It's used to maintain statfs cache for the target.
106  * The function fills data from the reply if successful and schedules another
107  * update.
108  *
109  * \param[in] env       LU environment provided by the caller
110  * \param[in] req       RPC replied
111  * \param[in] aa        callback data
112  * \param[in] rc        RPC result
113  *
114  * \retval 0            on success
115  * \retval negative     negated errno on error
116  */
117 static int osp_statfs_interpret(const struct lu_env *env,
118                                 struct ptlrpc_request *req,
119                                 union ptlrpc_async_args *aa, int rc)
120 {
121         struct obd_import       *imp = req->rq_import;
122         struct obd_statfs       *msfs;
123         struct osp_device       *d;
124
125         ENTRY;
126
127         aa = ptlrpc_req_async_args(req);
128         d = aa->pointer_arg[0];
129         LASSERT(d);
130
131         if (rc != 0)
132                 GOTO(out, rc);
133
134         msfs = req_capsule_server_get(&req->rq_pill, &RMF_OBD_STATFS);
135         if (msfs == NULL)
136                 GOTO(out, rc = -EPROTO);
137
138         d->opd_statfs = *msfs;
139
140         osp_pre_update_status(d, rc);
141
142         /* schedule next update */
143         d->opd_statfs_fresh_till = cfs_time_shift(d->opd_statfs_maxage);
144         mod_timer(&d->opd_statfs_timer, d->opd_statfs_fresh_till);
145         d->opd_statfs_update_in_progress = 0;
146
147         CDEBUG(D_CACHE, "updated statfs %p\n", d);
148
149         RETURN(0);
150 out:
151         /* couldn't update statfs, try again as soon as possible */
152         if (d->opd_pre != NULL && osp_precreate_running(d))
153                 wake_up(&d->opd_pre_waitq);
154
155         if (req->rq_import_generation == imp->imp_generation)
156                 CDEBUG(D_CACHE, "%s: couldn't update statfs: rc = %d\n",
157                        d->opd_obd->obd_name, rc);
158         RETURN(rc);
159 }
160
161 /**
162  * Send OST_STATFS RPC
163  *
164  * Sends OST_STATFS RPC to refresh cached statfs data for the target.
165  * Also disables scheduled updates as times OSP may need to refresh
166  * statfs data before expiration. The function doesn't block, instead
167  * an interpretation callback osp_statfs_interpret() is used.
168  *
169  * \param[in] d         OSP device
170  */
171 static int osp_statfs_update(struct osp_device *d)
172 {
173         struct ptlrpc_request   *req;
174         struct obd_import       *imp;
175         union ptlrpc_async_args *aa;
176         int                      rc;
177
178         ENTRY;
179
180         CDEBUG(D_CACHE, "going to update statfs\n");
181
182         imp = d->opd_obd->u.cli.cl_import;
183         LASSERT(imp);
184
185         req = ptlrpc_request_alloc(imp, &RQF_OST_STATFS);
186         if (req == NULL)
187                 RETURN(-ENOMEM);
188
189         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_STATFS);
190         if (rc) {
191                 ptlrpc_request_free(req);
192                 RETURN(rc);
193         }
194         ptlrpc_request_set_replen(req);
195         req->rq_request_portal = OST_CREATE_PORTAL;
196         ptlrpc_at_set_req_timeout(req);
197
198         req->rq_interpret_reply = (ptlrpc_interpterer_t)osp_statfs_interpret;
199         aa = ptlrpc_req_async_args(req);
200         aa->pointer_arg[0] = d;
201
202         /*
203          * no updates till reply
204          */
205         del_timer(&d->opd_statfs_timer);
206         d->opd_statfs_fresh_till = cfs_time_shift(obd_timeout * 1000);
207         d->opd_statfs_update_in_progress = 1;
208
209         ptlrpcd_add_req(req);
210
211         RETURN(0);
212 }
213
214 /**
215  * Schedule an immediate update for statfs data
216  *
217  * If cached statfs data claim no free space, but OSP has got a request to
218  * destroy an object (so release some space probably), then we may need to
219  * refresh cached statfs data sooner than planned. The function checks there
220  * is no statfs update going and schedules immediate update if so.
221  * XXX: there might be a case where removed object(s) do not add free space (empty
222  * object). If the number of such deletions is high, then we can start to update
223  * statfs too often causing a RPC storm. some throttling is needed...
224  *
225  * \param[in] d         OSP device where statfs data needs to be refreshed
226  */
227 void osp_statfs_need_now(struct osp_device *d)
228 {
229         if (!d->opd_statfs_update_in_progress) {
230                 /*
231                  * if current status is -ENOSPC (lack of free space on OST)
232                  * then we should poll OST immediately once object destroy
233                  * is replied
234                  */
235                 d->opd_statfs_fresh_till = cfs_time_shift(-1);
236                 del_timer(&d->opd_statfs_timer);
237                 wake_up(&d->opd_pre_waitq);
238         }
239 }
240
241 /**
242  * Return number of precreated objects
243  *
244  * A simple helper to calculate the number of precreated objects on the device.
245  *
246  * \param[in] env       LU environment provided by the caller
247  * \param[in] osp       OSP device
248  *
249  * \retval              the number of the precreated objects
250  */
251 static inline int osp_objs_precreated(const struct lu_env *env,
252                                       struct osp_device *osp)
253 {
254         return osp_fid_diff(&osp->opd_pre_last_created_fid,
255                             &osp->opd_pre_used_fid);
256 }
257
258 /**
259  * Check pool of precreated objects is nearly empty
260  *
261  * We should not wait till the pool of the precreated objects is exhausted,
262  * because then there will be a long period of OSP being unavailable for the
263  * new creations due to lenghty precreate RPC. Instead we ask for another
264  * precreation ahead and hopefully have it ready before the current pool is
265  * empty. Notice this function relies on an external locking.
266  *
267  * \param[in] env       LU environment provided by the caller
268  * \param[in] d         OSP device
269  *
270  * \retval              0 - current pool is good enough, 1 - time to precreate
271  */
272 static inline int osp_precreate_near_empty_nolock(const struct lu_env *env,
273                                                   struct osp_device *d)
274 {
275         int window = osp_objs_precreated(env, d);
276
277         /* don't consider new precreation till OST is healty and
278          * has free space */
279         return ((window - d->opd_pre_reserved < d->opd_pre_create_count / 2) &&
280                 (d->opd_pre_status == 0));
281 }
282
283 /**
284  * Check pool of precreated objects
285  *
286  * This is protected version of osp_precreate_near_empty_nolock(), check that
287  * for the details.
288  *
289  * \param[in] env       LU environment provided by the caller
290  * \param[in] d         OSP device
291  *
292  * \retval              0 - current pool is good enough, 1 - time to precreate
293  */
294 static inline int osp_precreate_near_empty(const struct lu_env *env,
295                                            struct osp_device *d)
296 {
297         int rc;
298
299         /* XXX: do we really need locking here? */
300         spin_lock(&d->opd_pre_lock);
301         rc = osp_precreate_near_empty_nolock(env, d);
302         spin_unlock(&d->opd_pre_lock);
303         return rc;
304 }
305
306 /**
307  * Check given sequence is empty
308  *
309  * Returns a binary result whether the given sequence has some IDs left
310  * or not. Find the details in osp_fid_end_seq(). This is a lock protected
311  * version of that function.
312  *
313  * \param[in] env       LU environment provided by the caller
314  * \param[in] osp       OSP device
315  *
316  * \retval              0 - current sequence has no IDs, 1 - otherwise
317  */
318 static inline int osp_create_end_seq(const struct lu_env *env,
319                                      struct osp_device *osp)
320 {
321         struct lu_fid *fid = &osp->opd_pre_used_fid;
322         int rc;
323
324         spin_lock(&osp->opd_pre_lock);
325         rc = osp_fid_end_seq(env, fid);
326         spin_unlock(&osp->opd_pre_lock);
327         return rc;
328 }
329
330 /**
331  * Write FID into into last_oid/last_seq file
332  *
333  * The function stores the sequence and the in-sequence id into two dedicated
334  * files. The sync argument can be used to request synchronous commit, so the
335  * function won't return until the updates are committed.
336  *
337  * \param[in] env       LU environment provided by the caller
338  * \param[in] osp       OSP device
339  * \param[in] fid       fid where sequence/id is taken
340  * \param[in] sync      update mode: 0 - asynchronously, 1 - synchronously
341  *
342  * \retval 0            on success
343  * \retval negative     negated errno on error
344  **/
345 int osp_write_last_oid_seq_files(struct lu_env *env, struct osp_device *osp,
346                                  struct lu_fid *fid, int sync)
347 {
348         struct osp_thread_info  *oti = osp_env_info(env);
349         struct lu_buf      *lb_oid = &oti->osi_lb;
350         struct lu_buf      *lb_oseq = &oti->osi_lb2;
351         loff_t             oid_off;
352         loff_t             oseq_off;
353         struct thandle    *th;
354         int                   rc;
355         ENTRY;
356
357         if (osp->opd_storage->dd_rdonly)
358                 RETURN(0);
359
360         /* Note: through f_oid is only 32 bits, it will also write 64 bits
361          * for oid to keep compatibility with the previous version. */
362         lb_oid->lb_buf = &fid->f_oid;
363         lb_oid->lb_len = sizeof(u64);
364         oid_off = sizeof(u64) * osp->opd_index;
365
366         lb_oseq->lb_buf = &fid->f_seq;
367         lb_oseq->lb_len = sizeof(u64);
368         oseq_off = sizeof(u64) * osp->opd_index;
369
370         th = dt_trans_create(env, osp->opd_storage);
371         if (IS_ERR(th))
372                 RETURN(PTR_ERR(th));
373
374         th->th_sync |= sync;
375         rc = dt_declare_record_write(env, osp->opd_last_used_oid_file,
376                                      lb_oid, oid_off, th);
377         if (rc != 0)
378                 GOTO(out, rc);
379
380         rc = dt_declare_record_write(env, osp->opd_last_used_seq_file,
381                                      lb_oseq, oseq_off, th);
382         if (rc != 0)
383                 GOTO(out, rc);
384
385         rc = dt_trans_start_local(env, osp->opd_storage, th);
386         if (rc != 0)
387                 GOTO(out, rc);
388
389         rc = dt_record_write(env, osp->opd_last_used_oid_file, lb_oid,
390                              &oid_off, th);
391         if (rc != 0) {
392                 CERROR("%s: can not write to last seq file: rc = %d\n",
393                         osp->opd_obd->obd_name, rc);
394                 GOTO(out, rc);
395         }
396         rc = dt_record_write(env, osp->opd_last_used_seq_file, lb_oseq,
397                              &oseq_off, th);
398         if (rc) {
399                 CERROR("%s: can not write to last seq file: rc = %d\n",
400                         osp->opd_obd->obd_name, rc);
401                 GOTO(out, rc);
402         }
403 out:
404         dt_trans_stop(env, osp->opd_storage, th);
405         RETURN(rc);
406 }
407
408 /**
409  * Switch to another sequence
410  *
411  * When a current sequence has no available IDs left, OSP has to switch to
412  * another new sequence. OSP requests it using the regular FLDB protocol
413  * and stores synchronously before that is used in precreated. This is needed
414  * to basically have the sequences referenced (not orphaned), otherwise it's
415  * possible that OST has some objects precreated and the clients have data
416  * written to it, but after MDT failover nobody refers those objects and OSP
417  * has no idea that the sequence need cleanup to be done.
418  * While this is very expensive operation, it's supposed to happen very very
419  * infrequently because sequence has 2^32 or 2^48 objects (depending on type)
420  *
421  * \param[in] env       LU environment provided by the caller
422  * \param[in] osp       OSP device
423  *
424  * \retval 0            on success
425  * \retval negative     negated errno on error
426  */
427 static int osp_precreate_rollover_new_seq(struct lu_env *env,
428                                           struct osp_device *osp)
429 {
430         struct lu_fid   *fid = &osp_env_info(env)->osi_fid;
431         struct lu_fid   *last_fid = &osp->opd_last_used_fid;
432         int             rc;
433         ENTRY;
434
435         rc = seq_client_get_seq(env, osp->opd_obd->u.cli.cl_seq, &fid->f_seq);
436         if (rc != 0) {
437                 CERROR("%s: alloc fid error: rc = %d\n",
438                        osp->opd_obd->obd_name, rc);
439                 RETURN(rc);
440         }
441
442         fid->f_oid = 1;
443         fid->f_ver = 0;
444         LASSERTF(fid_seq(fid) != fid_seq(last_fid),
445                  "fid "DFID", last_fid "DFID"\n", PFID(fid),
446                  PFID(last_fid));
447
448         rc = osp_write_last_oid_seq_files(env, osp, fid, 1);
449         if (rc != 0) {
450                 CERROR("%s: Can not update oid/seq file: rc = %d\n",
451                        osp->opd_obd->obd_name, rc);
452                 RETURN(rc);
453         }
454
455         LCONSOLE_INFO("%s: update sequence from %#llx to %#llx\n",
456                       osp->opd_obd->obd_name, fid_seq(last_fid),
457                       fid_seq(fid));
458         /* Update last_xxx to the new seq */
459         spin_lock(&osp->opd_pre_lock);
460         osp->opd_last_used_fid = *fid;
461         osp->opd_gap_start_fid = *fid;
462         osp->opd_pre_used_fid = *fid;
463         osp->opd_pre_last_created_fid = *fid;
464         spin_unlock(&osp->opd_pre_lock);
465
466         RETURN(rc);
467 }
468
469 /**
470  * Find IDs available in current sequence
471  *
472  * The function calculates the highest possible ID and the number of IDs
473  * available in the current sequence OSP is using. The number is limited
474  * artifically by the caller (grow param) and the number of IDs available
475  * in the sequence by nature. The function doesn't require an external
476  * locking.
477  *
478  * \param[in] env       LU environment provided by the caller
479  * \param[in] osp       OSP device
480  * \param[in] fid       FID the caller wants to start with
481  * \param[in] grow      how many the caller wants
482  * \param[out] fid      the highest calculated FID
483  * \param[out] grow     the number of available IDs calculated
484  *
485  * \retval              0 on success, 1 - the sequence is empty
486  */
487 static int osp_precreate_fids(const struct lu_env *env, struct osp_device *osp,
488                               struct lu_fid *fid, int *grow)
489 {
490         struct osp_thread_info  *osi = osp_env_info(env);
491         __u64                   end;
492         int                     i = 0;
493
494         if (fid_is_idif(fid)) {
495                 struct lu_fid   *last_fid;
496                 struct ost_id   *oi = &osi->osi_oi;
497                 int rc;
498
499                 spin_lock(&osp->opd_pre_lock);
500                 last_fid = &osp->opd_pre_last_created_fid;
501                 fid_to_ostid(last_fid, oi);
502                 end = min(ostid_id(oi) + *grow, IDIF_MAX_OID);
503                 *grow = end - ostid_id(oi);
504                 rc = ostid_set_id(oi, ostid_id(oi) + *grow);
505                 spin_unlock(&osp->opd_pre_lock);
506
507                 if (*grow == 0 || rc)
508                         return 1;
509
510                 ostid_to_fid(fid, oi, osp->opd_index);
511                 return 0;
512         }
513
514         spin_lock(&osp->opd_pre_lock);
515         *fid = osp->opd_pre_last_created_fid;
516         end = fid->f_oid;
517         end = min((end + *grow), (__u64)LUSTRE_DATA_SEQ_MAX_WIDTH);
518         *grow = end - fid->f_oid;
519         fid->f_oid += end - fid->f_oid;
520         spin_unlock(&osp->opd_pre_lock);
521
522         CDEBUG(D_INFO, "Expect %d, actual %d ["DFID" -- "DFID"]\n",
523                *grow, i, PFID(fid), PFID(&osp->opd_pre_last_created_fid));
524
525         return *grow > 0 ? 0 : 1;
526 }
527
528 /**
529  * Prepare and send precreate RPC
530  *
531  * The function finds how many objects should be precreated.  Then allocates,
532  * prepares and schedules precreate RPC synchronously. Upon reply the function
533  * wake ups the threads waiting for the new objects on this target. If the
534  * target wasn't able to create all the objects requested, then the next
535  * precreate will be asking less objects (i.e. slow precreate down).
536  *
537  * \param[in] env       LU environment provided by the caller
538  * \param[in] d         OSP device
539  *
540  * \retval 0            on success
541  * \retval negative     negated errno on error
542  **/
543 static int osp_precreate_send(const struct lu_env *env, struct osp_device *d)
544 {
545         struct osp_thread_info  *oti = osp_env_info(env);
546         struct ptlrpc_request   *req;
547         struct obd_import       *imp;
548         struct ost_body         *body;
549         int                      rc, grow, diff;
550         struct lu_fid           *fid = &oti->osi_fid;
551         ENTRY;
552
553         /* don't precreate new objects till OST healthy and has free space */
554         if (unlikely(d->opd_pre_status)) {
555                 CDEBUG(D_INFO, "%s: don't send new precreate: rc = %d\n",
556                        d->opd_obd->obd_name, d->opd_pre_status);
557                 RETURN(0);
558         }
559
560         /*
561          * if not connection/initialization is compeleted, ignore
562          */
563         imp = d->opd_obd->u.cli.cl_import;
564         LASSERT(imp);
565
566         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
567         if (req == NULL)
568                 RETURN(-ENOMEM);
569         req->rq_request_portal = OST_CREATE_PORTAL;
570         /* we should not resend create request - anyway we will have delorphan
571          * and kill these objects */
572         req->rq_no_delay = req->rq_no_resend = 1;
573
574         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
575         if (rc) {
576                 ptlrpc_request_free(req);
577                 RETURN(rc);
578         }
579
580         LASSERT(d->opd_pre->osp_pre_delorphan_sent != 0);
581         spin_lock(&d->opd_pre_lock);
582         if (d->opd_pre_create_count > d->opd_pre_max_create_count / 2)
583                 d->opd_pre_create_count = d->opd_pre_max_create_count / 2;
584         grow = d->opd_pre_create_count;
585         spin_unlock(&d->opd_pre_lock);
586
587         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
588         LASSERT(body);
589
590         *fid = d->opd_pre_last_created_fid;
591         rc = osp_precreate_fids(env, d, fid, &grow);
592         if (rc == 1) {
593                 /* Current seq has been used up*/
594                 if (!osp_is_fid_client(d)) {
595                         osp_pre_update_status(d, -ENOSPC);
596                         rc = -ENOSPC;
597                 }
598                 wake_up(&d->opd_pre_waitq);
599                 GOTO(out_req, rc);
600         }
601
602         if (!osp_is_fid_client(d)) {
603                 /* Non-FID client will always send seq 0 because of
604                  * compatiblity */
605                 LASSERTF(fid_is_idif(fid), "Invalid fid "DFID"\n", PFID(fid));
606                 fid->f_seq = 0;
607         }
608
609         fid_to_ostid(fid, &body->oa.o_oi);
610         body->oa.o_valid = OBD_MD_FLGROUP;
611
612         ptlrpc_request_set_replen(req);
613
614         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_FAKE_PRECREATE))
615                 GOTO(ready, rc = 0);
616
617         rc = ptlrpc_queue_wait(req);
618         if (rc) {
619                 CERROR("%s: can't precreate: rc = %d\n", d->opd_obd->obd_name,
620                        rc);
621                 GOTO(out_req, rc);
622         }
623         LASSERT(req->rq_transno == 0);
624
625         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
626         if (body == NULL)
627                 GOTO(out_req, rc = -EPROTO);
628
629         ostid_to_fid(fid, &body->oa.o_oi, d->opd_index);
630
631 ready:
632         if (osp_fid_diff(fid, &d->opd_pre_used_fid) <= 0) {
633                 CERROR("%s: precreate fid "DFID" < local used fid "DFID
634                        ": rc = %d\n", d->opd_obd->obd_name,
635                        PFID(fid), PFID(&d->opd_pre_used_fid), -ESTALE);
636                 GOTO(out_req, rc = -ESTALE);
637         }
638
639         diff = osp_fid_diff(fid, &d->opd_pre_last_created_fid);
640
641         spin_lock(&d->opd_pre_lock);
642         if (diff < grow) {
643                 /* the OST has not managed to create all the
644                  * objects we asked for */
645                 d->opd_pre_create_count = max(diff, OST_MIN_PRECREATE);
646                 d->opd_pre_create_slow = 1;
647         } else {
648                 /* the OST is able to keep up with the work,
649                  * we could consider increasing create_count
650                  * next time if needed */
651                 d->opd_pre_create_slow = 0;
652         }
653
654         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
655         fid_to_ostid(fid, &body->oa.o_oi);
656
657         d->opd_pre_last_created_fid = *fid;
658         spin_unlock(&d->opd_pre_lock);
659
660         CDEBUG(D_HA, "%s: current precreated pool: "DFID"-"DFID"\n",
661                d->opd_obd->obd_name, PFID(&d->opd_pre_used_fid),
662                PFID(&d->opd_pre_last_created_fid));
663 out_req:
664         /* now we can wakeup all users awaiting for objects */
665         osp_pre_update_status(d, rc);
666         wake_up(&d->opd_pre_user_waitq);
667
668         ptlrpc_req_finished(req);
669         RETURN(rc);
670 }
671
672 /**
673  * Get last precreated object from target (OST)
674  *
675  * Sends synchronous RPC to the target (OST) to learn the last precreated
676  * object. This later is used to remove all unused objects (cleanup orphan
677  * procedure). Also, the next object after one we got will be used as a
678  * starting point for the new precreates.
679  *
680  * \param[in] env       LU environment provided by the caller
681  * \param[in] d         OSP device
682  *
683  * \retval 0            on success
684  * \retval negative     negated errno on error
685  **/
686 static int osp_get_lastfid_from_ost(const struct lu_env *env,
687                                     struct osp_device *d)
688 {
689         struct ptlrpc_request   *req = NULL;
690         struct obd_import       *imp;
691         struct lu_fid           *last_fid;
692         char                    *tmp;
693         int                     rc;
694         ENTRY;
695
696         imp = d->opd_obd->u.cli.cl_import;
697         LASSERT(imp);
698
699         req = ptlrpc_request_alloc(imp, &RQF_OST_GET_INFO_LAST_FID);
700         if (req == NULL)
701                 RETURN(-ENOMEM);
702
703         req_capsule_set_size(&req->rq_pill, &RMF_GETINFO_KEY, RCL_CLIENT,
704                              sizeof(KEY_LAST_FID));
705
706         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_GET_INFO);
707         if (rc) {
708                 ptlrpc_request_free(req);
709                 RETURN(rc);
710         }
711
712         tmp = req_capsule_client_get(&req->rq_pill, &RMF_GETINFO_KEY);
713         memcpy(tmp, KEY_LAST_FID, sizeof(KEY_LAST_FID));
714
715         req->rq_no_delay = req->rq_no_resend = 1;
716         last_fid = req_capsule_client_get(&req->rq_pill, &RMF_FID);
717         fid_cpu_to_le(last_fid, &d->opd_last_used_fid);
718
719         ptlrpc_request_set_replen(req);
720
721         rc = ptlrpc_queue_wait(req);
722         if (rc) {
723                 /* bad-bad OST.. let sysadm sort this out */
724                 if (rc == -ENOTSUPP) {
725                         CERROR("%s: server does not support FID: rc = %d\n",
726                                d->opd_obd->obd_name, -ENOTSUPP);
727                 }
728                 ptlrpc_set_import_active(imp, 0);
729                 GOTO(out, rc);
730         }
731
732         last_fid = req_capsule_server_get(&req->rq_pill, &RMF_FID);
733         if (last_fid == NULL) {
734                 CERROR("%s: Got last_fid failed.\n", d->opd_obd->obd_name);
735                 GOTO(out, rc = -EPROTO);
736         }
737
738         if (!fid_is_sane(last_fid)) {
739                 CERROR("%s: Got insane last_fid "DFID"\n",
740                        d->opd_obd->obd_name, PFID(last_fid));
741                 GOTO(out, rc = -EPROTO);
742         }
743
744         /* Only update the last used fid, if the OST has objects for
745          * this sequence, i.e. fid_oid > 0 */
746         if (fid_oid(last_fid) > 0)
747                 d->opd_last_used_fid = *last_fid;
748
749         CDEBUG(D_HA, "%s: Got last_fid "DFID"\n", d->opd_obd->obd_name,
750                PFID(last_fid));
751
752 out:
753         ptlrpc_req_finished(req);
754         RETURN(rc);
755 }
756
757 /**
758  * Cleanup orphans on OST
759  *
760  * This function is called in a contex of a dedicated thread handling
761  * all the precreation suff. The function waits till local recovery
762  * is complete, then identify all the unreferenced objects (orphans)
763  * using the highest ID referenced by a local and the highest object
764  * precreated by the target. The found range is a subject to removal
765  * using specially flagged RPC. During this process OSP is marked
766  * unavailable for new objects.
767  *
768  * \param[in] env       LU environment provided by the caller
769  * \param[in] d         OSP device
770  *
771  * \retval 0            on success
772  * \retval negative     negated errno on error
773  */
774 static int osp_precreate_cleanup_orphans(struct lu_env *env,
775                                          struct osp_device *d)
776 {
777         struct osp_thread_info  *osi = osp_env_info(env);
778         struct lu_fid           *last_fid = &osi->osi_fid;
779         struct ptlrpc_request   *req = NULL;
780         struct obd_import       *imp;
781         struct ost_body         *body;
782         struct l_wait_info       lwi = { 0 };
783         int                      update_status = 0;
784         int                      rc;
785         int                      diff;
786         struct lu_fid            fid;
787
788         ENTRY;
789
790         /*
791          * wait for local recovery to finish, so we can cleanup orphans.
792          * orphans are all objects since "last used" (assigned).
793          * consider reserved objects as created otherwise we can get into
794          * a livelock when one blocked thread holding a reservation can
795          * block recovery. see LU-8367 for the details. in some cases this
796          * can result in gaps (i.e. leaked objects), but we've got LFSCK...
797          *
798          * do not allow new reservations because they may end up getting
799          * orphans being cleaned up below. so we block new reservations.
800          */
801         spin_lock(&d->opd_pre_lock);
802         d->opd_pre_recovering = 1;
803         spin_unlock(&d->opd_pre_lock);
804         /*
805          * The locking above makes sure the opd_pre_reserved check below will
806          * catch all osp_precreate_reserve() calls who find
807          * "!opd_pre_recovering".
808          */
809         l_wait_event(d->opd_pre_waitq, d->opd_recovery_completed ||
810                      !osp_precreate_running(d) || d->opd_got_disconnected,
811                      &lwi);
812         if (!osp_precreate_running(d) || d->opd_got_disconnected)
813                 GOTO(out, rc = -EAGAIN);
814
815         *last_fid = d->opd_last_used_fid;
816         /* The OSP should already get the valid seq now */
817         LASSERT(!fid_is_zero(last_fid));
818         if (fid_oid(&d->opd_last_used_fid) < 2) {
819                 /* lastfid looks strange... ask OST */
820                 rc = osp_get_lastfid_from_ost(env, d);
821                 if (rc)
822                         GOTO(out, rc);
823         }
824
825         imp = d->opd_obd->u.cli.cl_import;
826         LASSERT(imp);
827
828         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
829         if (req == NULL)
830                 GOTO(out, rc = -ENOMEM);
831
832         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
833         if (rc) {
834                 ptlrpc_request_free(req);
835                 req = NULL;
836                 GOTO(out, rc);
837         }
838
839         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
840         if (body == NULL)
841                 GOTO(out, rc = -EPROTO);
842
843         body->oa.o_flags = 0;
844         body->oa.o_valid = OBD_MD_FLFLAGS | OBD_MD_FLGROUP;
845
846         /* unless this is the very first DELORPHAN (when we really
847          * can destroy some orphans), just tell OST to recreate
848          * missing objects in our precreate pool */
849         spin_lock(&d->opd_pre_lock);
850         if (d->opd_pre->osp_pre_delorphan_sent) {
851                 fid = d->opd_pre_last_created_fid;
852         } else {
853                 fid = d->opd_last_used_fid;
854                 body->oa.o_flags = OBD_FL_DELORPHAN;
855         }
856         spin_unlock(&d->opd_pre_lock);
857         fid_to_ostid(&fid, &body->oa.o_oi);
858
859         CDEBUG(D_HA, "%s: going to cleanup orphans since "DFID"\n",
860                d->opd_obd->obd_name, PFID(&fid));
861
862         ptlrpc_request_set_replen(req);
863
864         /* Don't resend the delorphan req */
865         req->rq_no_resend = req->rq_no_delay = 1;
866
867         rc = ptlrpc_queue_wait(req);
868         if (rc) {
869                 update_status = 1;
870                 GOTO(out, rc);
871         }
872
873         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
874         if (body == NULL)
875                 GOTO(out, rc = -EPROTO);
876
877         /*
878          * OST provides us with id new pool starts from in body->oa.o_id
879          */
880         ostid_to_fid(last_fid, &body->oa.o_oi, d->opd_index);
881
882         spin_lock(&d->opd_pre_lock);
883         diff = osp_fid_diff(&fid, last_fid);
884         if (diff > 0) {
885                 d->opd_pre_create_count = OST_MIN_PRECREATE + diff;
886                 d->opd_pre_last_created_fid = *last_fid;
887         } else {
888                 d->opd_pre_create_count = OST_MIN_PRECREATE;
889                 d->opd_pre_last_created_fid = *last_fid;
890         }
891         /*
892          * This empties the pre-creation pool and effectively blocks any new
893          * reservations.
894          */
895         LASSERT(fid_oid(&d->opd_pre_last_created_fid) <=
896                 LUSTRE_DATA_SEQ_MAX_WIDTH);
897         if (d->opd_pre->osp_pre_delorphan_sent == 0)
898                 d->opd_pre_used_fid = d->opd_pre_last_created_fid;
899         d->opd_pre_create_slow = 0;
900         spin_unlock(&d->opd_pre_lock);
901         d->opd_pre->osp_pre_delorphan_sent = 1;
902
903         CDEBUG(D_HA, "%s: Got last_id "DFID" from OST, last_created "DFID
904                "last_used is "DFID"\n", d->opd_obd->obd_name, PFID(last_fid),
905                PFID(&d->opd_pre_last_created_fid), PFID(&d->opd_last_used_fid));
906 out:
907         if (req)
908                 ptlrpc_req_finished(req);
909
910         /*
911          * If rc is zero, the pre-creation window should have been emptied.
912          * Since waking up the herd would be useless without pre-created
913          * objects, we defer the signal to osp_precreate_send() in that case.
914          */
915         if (rc != 0) {
916                 if (update_status) {
917                         CERROR("%s: cannot cleanup orphans: rc = %d\n",
918                                d->opd_obd->obd_name, rc);
919                         /* we can't proceed from here, OST seem to
920                          * be in a bad shape, better to wait for
921                          * a new instance of the server and repeat
922                          * from the beginning. notify possible waiters
923                          * this OSP isn't quite functional yet */
924                         osp_pre_update_status(d, rc);
925                 } else {
926                         wake_up(&d->opd_pre_user_waitq);
927                 }
928         } else {
929                 spin_lock(&d->opd_pre_lock);
930                 d->opd_pre_recovering = 0;
931                 spin_unlock(&d->opd_pre_lock);
932         }
933
934         RETURN(rc);
935 }
936
937 /**
938  * Update precreate status using statfs data
939  *
940  * The function decides whether this OSP should be used for new objects.
941  * IOW, whether this OST is used up or has some free space. Cached statfs
942  * data is used to make this decision. If the latest result of statfs
943  * request (rc argument) is not success, then just mark OSP unavailable
944  * right away.
945
946  * Add a bit of hysteresis so this flag isn't continually flapping,
947  * and ensure that new files don't get extremely fragmented due to
948  * only a small amount of available space in the filesystem.
949  * We want to set the ENOSPC when there is less than reserved size
950  * free and clear it when there is at least 2*reserved size free space.
951  * the function updates current precreation status used: functional or not
952  *
953  * \param[in] d         OSP device
954  * \param[in] rc        new precreate status for device \a d
955  *
956  * \retval 0            on success
957  * \retval negative     negated errno on error
958  */
959 void osp_pre_update_status(struct osp_device *d, int rc)
960 {
961         struct obd_statfs       *msfs = &d->opd_statfs;
962         int                      old = d->opd_pre_status;
963         __u64                    available;
964
965         d->opd_pre_status = rc;
966         if (rc)
967                 goto out;
968
969         if (likely(msfs->os_type)) {
970                 if (unlikely(d->opd_reserved_mb_high == 0 &&
971                              d->opd_reserved_mb_low == 0)) {
972                         /* Use ~0.1% by default to disable object allocation,
973                          * and ~0.2% to enable, size in MB, set both watermark
974                          */
975                         spin_lock(&d->opd_pre_lock);
976                         if (d->opd_reserved_mb_high == 0 &&
977                             d->opd_reserved_mb_low == 0) {
978                                 d->opd_reserved_mb_low =
979                                         ((msfs->os_bsize >> 10) *
980                                         msfs->os_blocks) >> 20;
981                                 if (d->opd_reserved_mb_low == 0)
982                                         d->opd_reserved_mb_low = 1;
983                                 d->opd_reserved_mb_high =
984                                         (d->opd_reserved_mb_low << 1) + 1;
985                         }
986                         spin_unlock(&d->opd_pre_lock);
987                 }
988                 /* in MB */
989                 available = (msfs->os_bavail * (msfs->os_bsize >> 10)) >> 10;
990                 if (msfs->os_ffree < 32)
991                         msfs->os_state |= OS_STATE_ENOINO;
992                 else if (msfs->os_ffree > 64)
993                         msfs->os_state &= ~OS_STATE_ENOINO;
994
995                 if (available < d->opd_reserved_mb_low)
996                         msfs->os_state |= OS_STATE_ENOSPC;
997                 else if (available > d->opd_reserved_mb_high)
998                         msfs->os_state &= ~OS_STATE_ENOSPC;
999                 if (msfs->os_state & (OS_STATE_ENOINO | OS_STATE_ENOSPC)) {
1000                         d->opd_pre_status = -ENOSPC;
1001                         if (old != -ENOSPC)
1002                                 CDEBUG(D_INFO, "%s: status: %llu blocks, %llu "
1003                                        "free, %llu avail, %llu MB avail, %u "
1004                                        "hwm -> %d: rc = %d\n",
1005                                        d->opd_obd->obd_name, msfs->os_blocks,
1006                                        msfs->os_bfree, msfs->os_bavail,
1007                                        available, d->opd_reserved_mb_high,
1008                                        d->opd_pre_status, rc);
1009                         CDEBUG(D_INFO,
1010                                "non-committed changes: %u, in progress: %u\n",
1011                                atomic_read(&d->opd_syn_changes),
1012                                atomic_read(&d->opd_syn_rpc_in_progress));
1013                 } else if (unlikely(old == -ENOSPC)) {
1014                         d->opd_pre_status = 0;
1015                         spin_lock(&d->opd_pre_lock);
1016                         d->opd_pre_create_slow = 0;
1017                         d->opd_pre_create_count = OST_MIN_PRECREATE;
1018                         spin_unlock(&d->opd_pre_lock);
1019                         wake_up(&d->opd_pre_waitq);
1020
1021                         CDEBUG(D_INFO, "%s: space available: %llu blocks, %llu"
1022                                " free, %llu avail, %lluMB avail, %u lwm"
1023                                " -> %d: rc = %d\n", d->opd_obd->obd_name,
1024                                msfs->os_blocks, msfs->os_bfree, msfs->os_bavail,
1025                                available, d->opd_reserved_mb_low,
1026                                d->opd_pre_status, rc);
1027                 }
1028         }
1029 out:
1030         wake_up(&d->opd_pre_user_waitq);
1031 }
1032
1033 /**
1034  * Initialize FID for precreation
1035  *
1036  * For a just created new target, a new sequence should be taken.
1037  * The function checks there is no IDIF in use (if the target was
1038  * added with the older version of Lustre), then requests a new
1039  * sequence from FLDB using the regular protocol. Then this new
1040  * sequence is stored on a persisten storage synchronously to prevent
1041  * possible object leakage (for the detail see the description for
1042  * osp_precreate_rollover_new_seq()).
1043  *
1044  * \param[in] osp       OSP device
1045  *
1046  * \retval 0            on success
1047  * \retval negative     negated errno on error
1048  */
1049 int osp_init_pre_fid(struct osp_device *osp)
1050 {
1051         struct lu_env           env;
1052         struct osp_thread_info  *osi;
1053         struct lu_client_seq    *cli_seq;
1054         struct lu_fid           *last_fid;
1055         int                     rc;
1056         ENTRY;
1057
1058         LASSERT(osp->opd_pre != NULL);
1059
1060         /* Let's check if the current last_seq/fid is valid,
1061          * otherwise request new sequence from the controller */
1062         if (osp_is_fid_client(osp) && osp->opd_group != 0) {
1063                 /* Non-MDT0 can only use normal sequence for
1064                  * OST objects */
1065                 if (fid_is_norm(&osp->opd_last_used_fid))
1066                         RETURN(0);
1067         } else {
1068                 /* Initially MDT0 will start with IDIF, after
1069                  * that it will request new sequence from the
1070                  * controller */
1071                 if (fid_is_idif(&osp->opd_last_used_fid) ||
1072                     fid_is_norm(&osp->opd_last_used_fid))
1073                         RETURN(0);
1074         }
1075
1076         if (!fid_is_zero(&osp->opd_last_used_fid))
1077                 CWARN("%s: invalid last used fid "DFID
1078                       ", try to get new sequence.\n",
1079                       osp->opd_obd->obd_name,
1080                       PFID(&osp->opd_last_used_fid));
1081
1082         rc = lu_env_init(&env, osp->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1083         if (rc) {
1084                 CERROR("%s: init env error: rc = %d\n",
1085                        osp->opd_obd->obd_name, rc);
1086                 RETURN(rc);
1087         }
1088
1089         osi = osp_env_info(&env);
1090         last_fid = &osi->osi_fid;
1091         fid_zero(last_fid);
1092         /* For a freshed fs, it will allocate a new sequence first */
1093         if (osp_is_fid_client(osp) && osp->opd_group != 0) {
1094                 cli_seq = osp->opd_obd->u.cli.cl_seq;
1095                 rc = seq_client_get_seq(&env, cli_seq, &last_fid->f_seq);
1096                 if (rc != 0) {
1097                         CERROR("%s: alloc fid error: rc = %d\n",
1098                                osp->opd_obd->obd_name, rc);
1099                         GOTO(out, rc);
1100                 }
1101         } else {
1102                 last_fid->f_seq = fid_idif_seq(0, osp->opd_index);
1103         }
1104         last_fid->f_oid = 1;
1105         last_fid->f_ver = 0;
1106
1107         spin_lock(&osp->opd_pre_lock);
1108         osp->opd_last_used_fid = *last_fid;
1109         osp->opd_pre_used_fid = *last_fid;
1110         osp->opd_pre_last_created_fid = *last_fid;
1111         spin_unlock(&osp->opd_pre_lock);
1112         rc = osp_write_last_oid_seq_files(&env, osp, last_fid, 1);
1113         if (rc != 0) {
1114                 CERROR("%s: write fid error: rc = %d\n",
1115                        osp->opd_obd->obd_name, rc);
1116                 GOTO(out, rc);
1117         }
1118 out:
1119         lu_env_fini(&env);
1120         RETURN(rc);
1121 }
1122
1123 /**
1124  * The core of precreate functionality
1125  *
1126  * The function implements the main precreation loop. Basically it
1127  * involves connecting to the target, precerate FID initialization,
1128  * identifying and removing orphans, then serving precreation. As
1129  * part of the latter, the thread is responsible for statfs data
1130  * updates. The precreation is mostly driven by another threads
1131  * asking for new OST objects - those askers wake the thread when
1132  * the number of precreated objects reach low watermark.
1133  * After a disconnect, the sequence above repeats. This is keep going
1134  * until the thread is requested to stop.
1135  *
1136  * \param[in] _arg      private data the thread (OSP device to handle)
1137  *
1138  * \retval 0            on success
1139  * \retval negative     negated errno on error
1140  */
1141 static int osp_precreate_thread(void *_arg)
1142 {
1143         struct osp_device       *d = _arg;
1144         struct ptlrpc_thread    *thread = &d->opd_pre_thread;
1145         struct l_wait_info       lwi = { 0 };
1146         struct l_wait_info       lwi2 = LWI_TIMEOUT(cfs_time_seconds(5),
1147                                                     back_to_sleep, NULL);
1148         struct lu_env            env;
1149         int                      rc;
1150
1151         ENTRY;
1152
1153         rc = lu_env_init(&env, d->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1154         if (rc) {
1155                 CERROR("%s: init env error: rc = %d\n", d->opd_obd->obd_name,
1156                        rc);
1157
1158                 spin_lock(&d->opd_pre_lock);
1159                 thread->t_flags = SVC_STOPPED;
1160                 spin_unlock(&d->opd_pre_lock);
1161                 wake_up(&thread->t_ctl_waitq);
1162
1163                 RETURN(rc);
1164         }
1165
1166         spin_lock(&d->opd_pre_lock);
1167         thread->t_flags = SVC_RUNNING;
1168         spin_unlock(&d->opd_pre_lock);
1169         wake_up(&thread->t_ctl_waitq);
1170
1171         while (osp_precreate_running(d)) {
1172                 /*
1173                  * need to be connected to OST
1174                  */
1175                 while (osp_precreate_running(d)) {
1176                         if (d->opd_pre_recovering &&
1177                             d->opd_imp_connected &&
1178                             !d->opd_got_disconnected)
1179                                 break;
1180                         l_wait_event(d->opd_pre_waitq,
1181                                      !osp_precreate_running(d) ||
1182                                      d->opd_new_connection,
1183                                      &lwi);
1184
1185                         if (!d->opd_new_connection)
1186                                 continue;
1187
1188                         d->opd_new_connection = 0;
1189                         d->opd_got_disconnected = 0;
1190                         break;
1191                 }
1192
1193                 if (!osp_precreate_running(d))
1194                         break;
1195
1196                 LASSERT(d->opd_obd->u.cli.cl_seq != NULL);
1197                 /* Sigh, fid client is not ready yet */
1198                 if (d->opd_obd->u.cli.cl_seq->lcs_exp == NULL)
1199                         continue;
1200
1201                 /* Init fid for osp_precreate if necessary */
1202                 rc = osp_init_pre_fid(d);
1203                 if (rc != 0) {
1204                         class_export_put(d->opd_exp);
1205                         d->opd_obd->u.cli.cl_seq->lcs_exp = NULL;
1206                         CERROR("%s: init pre fid error: rc = %d\n",
1207                                d->opd_obd->obd_name, rc);
1208                         continue;
1209                 }
1210
1211                 if (osp_statfs_update(d)) {
1212                         l_wait_event(d->opd_pre_waitq,
1213                                      !osp_precreate_running(d), &lwi2);
1214                         continue;
1215                 }
1216
1217                 /*
1218                  * Clean up orphans or recreate missing objects.
1219                  */
1220                 rc = osp_precreate_cleanup_orphans(&env, d);
1221                 if (rc != 0) {
1222                         schedule_timeout_interruptible(cfs_time_seconds(1));
1223                         continue;
1224                 }
1225                 /*
1226                  * connected, can handle precreates now
1227                  */
1228                 while (osp_precreate_running(d)) {
1229                         l_wait_event(d->opd_pre_waitq,
1230                                      !osp_precreate_running(d) ||
1231                                      osp_precreate_near_empty(&env, d) ||
1232                                      osp_statfs_need_update(d) ||
1233                                      d->opd_got_disconnected, &lwi);
1234
1235                         if (!osp_precreate_running(d))
1236                                 break;
1237
1238                         /* something happened to the connection
1239                          * have to start from the beginning */
1240                         if (d->opd_got_disconnected)
1241                                 break;
1242
1243                         if (osp_statfs_need_update(d))
1244                                 if (osp_statfs_update(d))
1245                                         break;
1246
1247                         /* To avoid handling different seq in precreate/orphan
1248                          * cleanup, it will hold precreate until current seq is
1249                          * used up. */
1250                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1251                             !osp_create_end_seq(&env, d)))
1252                                 continue;
1253
1254                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1255                                      osp_create_end_seq(&env, d))) {
1256                                 LCONSOLE_INFO("%s:%#llx is used up."
1257                                               " Update to new seq\n",
1258                                               d->opd_obd->obd_name,
1259                                          fid_seq(&d->opd_pre_last_created_fid));
1260                                 rc = osp_precreate_rollover_new_seq(&env, d);
1261                                 if (rc)
1262                                         continue;
1263                         }
1264
1265                         if (osp_precreate_near_empty(&env, d)) {
1266                                 rc = osp_precreate_send(&env, d);
1267                                 /* osp_precreate_send() sets opd_pre_status
1268                                  * in case of error, that prevent the using of
1269                                  * failed device. */
1270                                 if (rc < 0 && rc != -ENOSPC &&
1271                                     rc != -ETIMEDOUT && rc != -ENOTCONN)
1272                                         CERROR("%s: cannot precreate objects:"
1273                                                " rc = %d\n",
1274                                                d->opd_obd->obd_name, rc);
1275                         }
1276                 }
1277         }
1278
1279         thread->t_flags = SVC_STOPPED;
1280         lu_env_fini(&env);
1281         wake_up(&thread->t_ctl_waitq);
1282
1283         RETURN(0);
1284 }
1285
1286 /**
1287  * Check when to stop to wait for precreate objects.
1288  *
1289  * The caller wanting a new OST object can't wait undefinitely. The
1290  * function checks for few conditions including available new OST
1291  * objects, disconnected OST, lack of space with no pending destroys,
1292  * etc. IOW, it checks whether the current OSP state is good to keep
1293  * waiting or it's better to give up.
1294  *
1295  * \param[in] env       LU environment provided by the caller
1296  * \param[in] d         OSP device
1297  *
1298  * \retval              0 - keep waiting, 1 - no luck
1299  */
1300 static int osp_precreate_ready_condition(const struct lu_env *env,
1301                                          struct osp_device *d)
1302 {
1303         if (d->opd_pre_recovering)
1304                 return 0;
1305
1306         /* ready if got enough precreated objects */
1307         /* we need to wait for others (opd_pre_reserved) and our object (+1) */
1308         if (d->opd_pre_reserved + 1 < osp_objs_precreated(env, d))
1309                 return 1;
1310
1311         /* ready if OST reported no space and no destroys in progress */
1312         if (atomic_read(&d->opd_syn_changes) +
1313             atomic_read(&d->opd_syn_rpc_in_progress) == 0 &&
1314             d->opd_pre_status == -ENOSPC)
1315                 return 1;
1316
1317         /* Bail out I/O fails to OST */
1318         if (d->opd_pre_status != 0 &&
1319             d->opd_pre_status != -EAGAIN &&
1320             d->opd_pre_status != -ENODEV &&
1321             d->opd_pre_status != -ENOTCONN &&
1322             d->opd_pre_status != -ENOSPC) {
1323                 /* DEBUG LU-3230 */
1324                 if (d->opd_pre_status != -EIO)
1325                         CERROR("%s: precreate failed opd_pre_status %d\n",
1326                                d->opd_obd->obd_name, d->opd_pre_status);
1327                 return 1;
1328         }
1329
1330         return 0;
1331 }
1332
1333 static int osp_precreate_timeout_condition(void *data)
1334 {
1335         struct osp_device *d = data;
1336
1337         CDEBUG(D_HA, "%s: slow creates, last="DFID", next="DFID", "
1338               "reserved=%llu, syn_changes=%u, "
1339               "syn_rpc_in_progress=%d, status=%d\n",
1340               d->opd_obd->obd_name, PFID(&d->opd_pre_last_created_fid),
1341               PFID(&d->opd_pre_used_fid), d->opd_pre_reserved,
1342               atomic_read(&d->opd_syn_changes),
1343               atomic_read(&d->opd_syn_rpc_in_progress),
1344               d->opd_pre_status);
1345
1346         return 1;
1347 }
1348
1349 /**
1350  * Reserve object in precreate pool
1351  *
1352  * When the caller wants to create a new object on this target (target
1353  * represented by the given OSP), it should declare this intention using
1354  * a regular ->dt_declare_create() OSD API method. Then OSP will be trying
1355  * to reserve an object in the existing precreated pool or wait up to
1356  * obd_timeout for the available object to appear in the pool (a dedicated
1357  * thread will be doing real precreation in background). The object can be
1358  * consumed later with osp_precreate_get_fid() or be released with call to
1359  * lu_object_put(). Notice the function doesn't reserve a specific ID, just
1360  * some ID. The actual ID assignment happen in osp_precreate_get_fid().
1361  * If the space on the target is short and there is a pending object destroy,
1362  * then the function forces local commit to speedup space release (see
1363  * osp_sync.c for the details).
1364  *
1365  * \param[in] env       LU environment provided by the caller
1366  * \param[in] d         OSP device
1367  *
1368  * \retval              0 on success
1369  * \retval              -ENOSPC when no space on OST
1370  * \retval              -EAGAIN try later, slow precreation in progress
1371  * \retval              -EIO when no access to OST
1372  */
1373 int osp_precreate_reserve(const struct lu_env *env, struct osp_device *d)
1374 {
1375         struct l_wait_info       lwi;
1376         cfs_time_t               expire = cfs_time_shift(obd_timeout);
1377         int                      precreated, rc;
1378
1379         ENTRY;
1380
1381         LASSERTF(osp_objs_precreated(env, d) >= 0, "Last created FID "DFID
1382                  "Next FID "DFID"\n", PFID(&d->opd_pre_last_created_fid),
1383                  PFID(&d->opd_pre_used_fid));
1384
1385         /* opd_pre_max_create_count 0 to not use specified OST. */
1386         if (d->opd_pre_max_create_count == 0)
1387                 RETURN(-ENOBUFS);
1388
1389         if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_OSP_PRECREATE_WAIT)) {
1390                 if (d->opd_index == cfs_fail_val)
1391                         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_OSP_PRECREATE_WAIT,
1392                                          obd_timeout);
1393         }
1394
1395         /*
1396          * wait till:
1397          *  - preallocation is done
1398          *  - no free space expected soon
1399          *  - can't connect to OST for too long (obd_timeout)
1400          *  - OST can allocate fid sequence.
1401          */
1402         while ((rc = d->opd_pre_status) == 0 || rc == -ENOSPC ||
1403                 rc == -ENODEV || rc == -EAGAIN || rc == -ENOTCONN) {
1404
1405                 /*
1406                  * increase number of precreations
1407                  */
1408                 precreated = osp_objs_precreated(env, d);
1409                 if (d->opd_pre_create_count < d->opd_pre_max_create_count &&
1410                     d->opd_pre_create_slow == 0 &&
1411                     precreated <= (d->opd_pre_create_count / 4 + 1)) {
1412                         spin_lock(&d->opd_pre_lock);
1413                         d->opd_pre_create_slow = 1;
1414                         d->opd_pre_create_count *= 2;
1415                         spin_unlock(&d->opd_pre_lock);
1416                 }
1417
1418                 spin_lock(&d->opd_pre_lock);
1419                 precreated = osp_objs_precreated(env, d);
1420                 if (precreated > d->opd_pre_reserved &&
1421                     !d->opd_pre_recovering) {
1422                         d->opd_pre_reserved++;
1423                         spin_unlock(&d->opd_pre_lock);
1424                         rc = 0;
1425
1426                         /* XXX: don't wake up if precreation is in progress */
1427                         if (osp_precreate_near_empty_nolock(env, d) &&
1428                            !osp_precreate_end_seq_nolock(env, d))
1429                                 wake_up(&d->opd_pre_waitq);
1430
1431                         break;
1432                 }
1433                 spin_unlock(&d->opd_pre_lock);
1434
1435                 /*
1436                  * all precreated objects have been used and no-space
1437                  * status leave us no chance to succeed very soon
1438                  * but if there is destroy in progress, then we should
1439                  * wait till that is done - some space might be released
1440                  */
1441                 if (unlikely(rc == -ENOSPC)) {
1442                         if (atomic_read(&d->opd_syn_changes)) {
1443                                 /* force local commit to release space */
1444                                 dt_commit_async(env, d->opd_storage);
1445                         }
1446                         if (atomic_read(&d->opd_syn_rpc_in_progress)) {
1447                                 /* just wait till destroys are done */
1448                                 /* see l_wait_even() few lines below */
1449                         }
1450                         if (atomic_read(&d->opd_syn_changes) +
1451                             atomic_read(&d->opd_syn_rpc_in_progress) == 0) {
1452                                 /* no hope for free space */
1453                                 break;
1454                         }
1455                 }
1456
1457                 /* XXX: don't wake up if precreation is in progress */
1458                 wake_up(&d->opd_pre_waitq);
1459
1460                 lwi = LWI_TIMEOUT(expire - cfs_time_current(),
1461                                 osp_precreate_timeout_condition, d);
1462                 if (cfs_time_aftereq(cfs_time_current(), expire)) {
1463                         rc = -ETIMEDOUT;
1464                         break;
1465                 }
1466
1467                 l_wait_event(d->opd_pre_user_waitq,
1468                              osp_precreate_ready_condition(env, d), &lwi);
1469         }
1470
1471         RETURN(rc);
1472 }
1473
1474 /**
1475  * Get a FID from precreation pool
1476  *
1477  * The function is a companion for osp_precreate_reserve() - it assigns
1478  * a specific FID from the precreate. The function should be called only
1479  * if the call to osp_precreate_reserve() was successful. The function
1480  * updates a local storage to remember the highest object ID referenced
1481  * by the node in the given sequence.
1482  *
1483  * A very importan details: this is supposed to be called once the
1484  * transaction is started, so on-disk update will be atomic with the
1485  * data (like LOVEA) refering this object. Then the object won't be leaked:
1486  * either it's referenced by the committed transaction or it's a subject
1487  * to the orphan cleanup procedure.
1488  *
1489  * \param[in] env       LU environment provided by the caller
1490  * \param[in] d         OSP device
1491  * \param[out] fid      generated FID
1492  *
1493  * \retval 0            on success
1494  * \retval negative     negated errno on error
1495  */
1496 int osp_precreate_get_fid(const struct lu_env *env, struct osp_device *d,
1497                           struct lu_fid *fid)
1498 {
1499         /* grab next id from the pool */
1500         spin_lock(&d->opd_pre_lock);
1501
1502         LASSERTF(osp_fid_diff(&d->opd_pre_used_fid,
1503                              &d->opd_pre_last_created_fid) < 0,
1504                  "next fid "DFID" last created fid "DFID"\n",
1505                  PFID(&d->opd_pre_used_fid),
1506                  PFID(&d->opd_pre_last_created_fid));
1507
1508         d->opd_pre_used_fid.f_oid++;
1509         memcpy(fid, &d->opd_pre_used_fid, sizeof(*fid));
1510         d->opd_pre_reserved--;
1511         /*
1512          * last_used_id must be changed along with getting new id otherwise
1513          * we might miscalculate gap causing object loss or leak
1514          */
1515         osp_update_last_fid(d, fid);
1516         spin_unlock(&d->opd_pre_lock);
1517
1518         /*
1519          * probably main thread suspended orphan cleanup till
1520          * all reservations are released, see comment in
1521          * osp_precreate_thread() just before orphan cleanup
1522          */
1523         if (unlikely(d->opd_pre_reserved == 0 && d->opd_pre_status))
1524                 wake_up(&d->opd_pre_waitq);
1525
1526         return 0;
1527 }
1528
1529 /*
1530  * Set size regular attribute on an object
1531  *
1532  * When a striping is created late, it's possible that size is already
1533  * initialized on the file. Then the new striping should inherit size
1534  * from the file. The function sets size on the object using the regular
1535  * protocol (OST_PUNCH).
1536  * XXX: should be re-implemented using OUT ?
1537  *
1538  * \param[in] env       LU environment provided by the caller
1539  * \param[in] dt        object
1540  * \param[in] size      size to set.
1541  *
1542  * \retval 0            on success
1543  * \retval negative     negated errno on error
1544  */
1545 int osp_object_truncate(const struct lu_env *env, struct dt_object *dt,
1546                         __u64 size)
1547 {
1548         struct osp_device       *d = lu2osp_dev(dt->do_lu.lo_dev);
1549         struct ptlrpc_request   *req = NULL;
1550         struct obd_import       *imp;
1551         struct ost_body         *body;
1552         struct obdo             *oa = NULL;
1553         int                      rc;
1554
1555         ENTRY;
1556
1557         imp = d->opd_obd->u.cli.cl_import;
1558         LASSERT(imp);
1559
1560         req = ptlrpc_request_alloc(imp, &RQF_OST_PUNCH);
1561         if (req == NULL)
1562                 RETURN(-ENOMEM);
1563
1564         /* XXX: capa support? */
1565         /* osc_set_capa_size(req, &RMF_CAPA1, capa); */
1566         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_PUNCH);
1567         if (rc) {
1568                 ptlrpc_request_free(req);
1569                 RETURN(rc);
1570         }
1571
1572         /*
1573          * XXX: decide how do we do here with resend
1574          * if we don't resend, then client may see wrong file size
1575          * if we do resend, then MDS thread can get stuck for quite long
1576          * and if we don't resend, then client will also get -EWOULDBLOCK !!
1577          * (see LU-7975 and sanity/test_27F use cases)
1578          * but let's decide not to resend/delay this truncate request to OST
1579          * and allow Client to decide to resend, in a less agressive way from
1580          * after_reply(), by returning -EINPROGRESS instead of
1581          * -EAGAIN/-EWOULDBLOCK upon return from ptlrpc_queue_wait() at the
1582          * end of this routine
1583          */
1584         req->rq_no_resend = req->rq_no_delay = 1;
1585
1586         req->rq_request_portal = OST_IO_PORTAL; /* bug 7198 */
1587         ptlrpc_at_set_req_timeout(req);
1588
1589         OBD_ALLOC_PTR(oa);
1590         if (oa == NULL)
1591                 GOTO(out, rc = -ENOMEM);
1592
1593         rc = fid_to_ostid(lu_object_fid(&dt->do_lu), &oa->o_oi);
1594         LASSERT(rc == 0);
1595         oa->o_size = size;
1596         oa->o_blocks = OBD_OBJECT_EOF;
1597         oa->o_valid = OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
1598                       OBD_MD_FLID | OBD_MD_FLGROUP;
1599
1600         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
1601         LASSERT(body);
1602         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa, oa);
1603
1604         /* XXX: capa support? */
1605         /* osc_pack_capa(req, body, capa); */
1606
1607         ptlrpc_request_set_replen(req);
1608
1609         rc = ptlrpc_queue_wait(req);
1610         if (rc) {
1611                 /* -EWOULDBLOCK/-EAGAIN means OST is unreachable at the moment
1612                  * since we have decided not to resend/delay, but this could
1613                  * lead to wrong size to be seen at Client side and even process
1614                  * trying to open to exit/fail if not itself handling -EAGAIN.
1615                  * So it should be better to return -EINPROGRESS instead and
1616                  * leave the decision to resend at Client side in after_reply()
1617                  */
1618                 if (rc == -EWOULDBLOCK) {
1619                         rc = -EINPROGRESS;
1620                         CDEBUG(D_HA, "returning -EINPROGRESS instead of "
1621                                "-EWOULDBLOCK/-EAGAIN to allow Client to "
1622                                "resend\n");
1623                 } else {
1624                         CERROR("can't punch object: %d\n", rc);
1625                 }
1626         }
1627 out:
1628         ptlrpc_req_finished(req);
1629         if (oa)
1630                 OBD_FREE_PTR(oa);
1631         RETURN(rc);
1632 }
1633
1634 /**
1635  * Initialize precreation functionality of OSP
1636  *
1637  * Prepares all the internal structures and starts the precreate thread
1638  *
1639  * \param[in] d         OSP device
1640  *
1641  * \retval 0            on success
1642  * \retval negative     negated errno on error
1643  */
1644 int osp_init_precreate(struct osp_device *d)
1645 {
1646         struct l_wait_info       lwi = { 0 };
1647         struct task_struct              *task;
1648
1649         ENTRY;
1650
1651         OBD_ALLOC_PTR(d->opd_pre);
1652         if (d->opd_pre == NULL)
1653                 RETURN(-ENOMEM);
1654
1655         /* initially precreation isn't ready */
1656         d->opd_pre_status = -EAGAIN;
1657         fid_zero(&d->opd_pre_used_fid);
1658         d->opd_pre_used_fid.f_oid = 1;
1659         fid_zero(&d->opd_pre_last_created_fid);
1660         d->opd_pre_last_created_fid.f_oid = 1;
1661         d->opd_pre_reserved = 0;
1662         d->opd_got_disconnected = 1;
1663         d->opd_pre_create_slow = 0;
1664         d->opd_pre_create_count = OST_MIN_PRECREATE;
1665         d->opd_pre_min_create_count = OST_MIN_PRECREATE;
1666         d->opd_pre_max_create_count = OST_MAX_PRECREATE;
1667         d->opd_reserved_mb_high = 0;
1668         d->opd_reserved_mb_low = 0;
1669
1670         spin_lock_init(&d->opd_pre_lock);
1671         init_waitqueue_head(&d->opd_pre_waitq);
1672         init_waitqueue_head(&d->opd_pre_user_waitq);
1673         thread_set_flags(&d->opd_pre_thread, SVC_INIT);
1674         init_waitqueue_head(&d->opd_pre_thread.t_ctl_waitq);
1675
1676         /*
1677          * Initialize statfs-related things
1678          */
1679         d->opd_statfs_maxage = 5; /* default update interval */
1680         d->opd_statfs_fresh_till = cfs_time_shift(-1000);
1681         CDEBUG(D_OTHER, "current %llu, fresh till %llu\n",
1682                (unsigned long long)cfs_time_current(),
1683                (unsigned long long)d->opd_statfs_fresh_till);
1684         setup_timer(&d->opd_statfs_timer, osp_statfs_timer_cb,
1685                     (unsigned long)d);
1686
1687         if (d->opd_storage->dd_rdonly)
1688                 RETURN(0);
1689
1690         /*
1691          * start thread handling precreation and statfs updates
1692          */
1693         task = kthread_run(osp_precreate_thread, d,
1694                            "osp-pre-%u-%u", d->opd_index, d->opd_group);
1695         if (IS_ERR(task)) {
1696                 CERROR("can't start precreate thread %ld\n", PTR_ERR(task));
1697                 RETURN(PTR_ERR(task));
1698         }
1699
1700         l_wait_event(d->opd_pre_thread.t_ctl_waitq,
1701                      osp_precreate_running(d) || osp_precreate_stopped(d),
1702                      &lwi);
1703
1704         RETURN(0);
1705 }
1706
1707 /**
1708  * Finish precreate functionality of OSP
1709  *
1710  *
1711  * Asks all the activity (the thread, update timer) to stop, then
1712  * wait till that is done.
1713  *
1714  * \param[in] d         OSP device
1715  */
1716 void osp_precreate_fini(struct osp_device *d)
1717 {
1718         struct ptlrpc_thread *thread = &d->opd_pre_thread;
1719         ENTRY;
1720
1721         del_timer(&d->opd_statfs_timer);
1722
1723         if (d->opd_pre == NULL)
1724                 RETURN_EXIT;
1725
1726         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
1727                 thread->t_flags = SVC_STOPPING;
1728                 wake_up(&d->opd_pre_waitq);
1729                 wait_event(thread->t_ctl_waitq, thread_is_stopped(thread));
1730         }
1731
1732         OBD_FREE_PTR(d->opd_pre);
1733         d->opd_pre = NULL;
1734
1735         EXIT;
1736 }
1737