Whamcloud - gitweb
076cc6a711d592e96d9664f2c60c9433c15804d8
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 2014, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osp/osp_sync.c
37  *
38  * Lustre OST Proxy Device
39  *
40  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
41  * Author: Mikhail Pershin <mike.pershin@intel.com>
42  * Author: Di Wang <di.wang@intel.com>
43  */
44
45 #define DEBUG_SUBSYSTEM S_MDS
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         cfs_timer_arm(&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         cfs_timer_disarm(&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, PDL_POLICY_ROUND, -1);
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 then 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                 cfs_timer_disarm(&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_grow_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         /* Note: through f_oid is only 32 bits, it will also write 64 bits
358          * for oid to keep compatibility with the previous version. */
359         lb_oid->lb_buf = &fid->f_oid;
360         lb_oid->lb_len = sizeof(u64);
361         oid_off = sizeof(u64) * osp->opd_index;
362
363         lb_oseq->lb_buf = &fid->f_seq;
364         lb_oseq->lb_len = sizeof(u64);
365         oseq_off = sizeof(u64) * osp->opd_index;
366
367         th = dt_trans_create(env, osp->opd_storage);
368         if (IS_ERR(th))
369                 RETURN(PTR_ERR(th));
370
371         th->th_sync |= sync;
372         rc = dt_declare_record_write(env, osp->opd_last_used_oid_file,
373                                      lb_oid, oid_off, th);
374         if (rc != 0)
375                 GOTO(out, rc);
376
377         rc = dt_declare_record_write(env, osp->opd_last_used_seq_file,
378                                      lb_oseq, oseq_off, th);
379         if (rc != 0)
380                 GOTO(out, rc);
381
382         rc = dt_trans_start_local(env, osp->opd_storage, th);
383         if (rc != 0)
384                 GOTO(out, rc);
385
386         rc = dt_record_write(env, osp->opd_last_used_oid_file, lb_oid,
387                              &oid_off, th);
388         if (rc != 0) {
389                 CERROR("%s: can not write to last seq file: rc = %d\n",
390                         osp->opd_obd->obd_name, rc);
391                 GOTO(out, rc);
392         }
393         rc = dt_record_write(env, osp->opd_last_used_seq_file, lb_oseq,
394                              &oseq_off, th);
395         if (rc) {
396                 CERROR("%s: can not write to last seq file: rc = %d\n",
397                         osp->opd_obd->obd_name, rc);
398                 GOTO(out, rc);
399         }
400 out:
401         dt_trans_stop(env, osp->opd_storage, th);
402         RETURN(rc);
403 }
404
405 /**
406  * Switch to another sequence
407  *
408  * When a current sequence has no available IDs left, OSP has to switch to
409  * another new sequence. OSP requests it using the regular FLDB protocol
410  * and stores synchronously before that is used in precreated. This is needed
411  * to basically have the sequences referenced (not orphaned), otherwise it's
412  * possible that OST has some objects precreated and the clients have data
413  * written to it, but after MDT failover nobody refers those objects and OSP
414  * has no idea that the sequence need cleanup to be done.
415  * While this is very expensive operation, it's supposed to happen very very
416  * infrequently because sequence has 2^32 or 2^48 objects (depending on type)
417  *
418  * \param[in] env       LU environment provided by the caller
419  * \param[in] osp       OSP device
420  *
421  * \retval 0            on success
422  * \retval negative     negated errno on error
423  */
424 static int osp_precreate_rollover_new_seq(struct lu_env *env,
425                                           struct osp_device *osp)
426 {
427         struct lu_fid   *fid = &osp_env_info(env)->osi_fid;
428         struct lu_fid   *last_fid = &osp->opd_last_used_fid;
429         int             rc;
430         ENTRY;
431
432         rc = seq_client_get_seq(env, osp->opd_obd->u.cli.cl_seq, &fid->f_seq);
433         if (rc != 0) {
434                 CERROR("%s: alloc fid error: rc = %d\n",
435                        osp->opd_obd->obd_name, rc);
436                 RETURN(rc);
437         }
438
439         fid->f_oid = 1;
440         fid->f_ver = 0;
441         LASSERTF(fid_seq(fid) != fid_seq(last_fid),
442                  "fid "DFID", last_fid "DFID"\n", PFID(fid),
443                  PFID(last_fid));
444
445         rc = osp_write_last_oid_seq_files(env, osp, fid, 1);
446         if (rc != 0) {
447                 CERROR("%s: Can not update oid/seq file: rc = %d\n",
448                        osp->opd_obd->obd_name, rc);
449                 RETURN(rc);
450         }
451
452         LCONSOLE_INFO("%s: update sequence from "LPX64" to "LPX64"\n",
453                       osp->opd_obd->obd_name, fid_seq(last_fid),
454                       fid_seq(fid));
455         /* Update last_xxx to the new seq */
456         spin_lock(&osp->opd_pre_lock);
457         osp->opd_last_used_fid = *fid;
458         osp->opd_gap_start_fid = *fid;
459         osp->opd_pre_used_fid = *fid;
460         osp->opd_pre_last_created_fid = *fid;
461         spin_unlock(&osp->opd_pre_lock);
462
463         RETURN(rc);
464 }
465
466 /**
467  * Find IDs available in current sequence
468  *
469  * The function calculates the highest possible ID and the number of IDs
470  * available in the current sequence OSP is using. The number is limited
471  * artifically by the caller (grow param) and the number of IDs available
472  * in the sequence by nature. The function doesn't require an external
473  * locking.
474  *
475  * \param[in] env       LU environment provided by the caller
476  * \param[in] osp       OSP device
477  * \param[in] fid       FID the caller wants to start with
478  * \param[in] grow      how many the caller wants
479  * \param[out] fid      the highest calculated FID
480  * \param[out] grow     the number of available IDs calculated
481  *
482  * \retval              0 on success, 1 - the sequence is empty
483  */
484 static int osp_precreate_fids(const struct lu_env *env, struct osp_device *osp,
485                               struct lu_fid *fid, int *grow)
486 {
487         struct osp_thread_info  *osi = osp_env_info(env);
488         __u64                   end;
489         int                     i = 0;
490
491         if (fid_is_idif(fid)) {
492                 struct lu_fid   *last_fid;
493                 struct ost_id   *oi = &osi->osi_oi;
494
495                 spin_lock(&osp->opd_pre_lock);
496                 last_fid = &osp->opd_pre_last_created_fid;
497                 fid_to_ostid(last_fid, oi);
498                 end = min(ostid_id(oi) + *grow, IDIF_MAX_OID);
499                 *grow = end - ostid_id(oi);
500                 ostid_set_id(oi, ostid_id(oi) + *grow);
501                 spin_unlock(&osp->opd_pre_lock);
502
503                 if (*grow == 0)
504                         return 1;
505
506                 ostid_to_fid(fid, oi, osp->opd_index);
507                 return 0;
508         }
509
510         spin_lock(&osp->opd_pre_lock);
511         *fid = osp->opd_pre_last_created_fid;
512         end = fid->f_oid;
513         end = min((end + *grow), (__u64)LUSTRE_DATA_SEQ_MAX_WIDTH);
514         *grow = end - fid->f_oid;
515         fid->f_oid += end - fid->f_oid;
516         spin_unlock(&osp->opd_pre_lock);
517
518         CDEBUG(D_INFO, "Expect %d, actual %d ["DFID" -- "DFID"]\n",
519                *grow, i, PFID(fid), PFID(&osp->opd_pre_last_created_fid));
520
521         return *grow > 0 ? 0 : 1;
522 }
523
524 /**
525  * Prepare and send precreate RPC
526  *
527  * The function finds how many objects should be precreated.  Then allocates,
528  * prepares and schedules precreate RPC synchronously. Upon reply the function
529  * wake ups the threads waiting for the new objects on this target. If the
530  * target wasn't able to create all the objects requested, then the next
531  * precreate will be asking less objects (i.e. slow precreate down).
532  *
533  * \param[in] env       LU environment provided by the caller
534  * \param[in] d         OSP device
535  *
536  * \retval 0            on success
537  * \retval negative     negated errno on error
538  **/
539 static int osp_precreate_send(const struct lu_env *env, struct osp_device *d)
540 {
541         struct osp_thread_info  *oti = osp_env_info(env);
542         struct ptlrpc_request   *req;
543         struct obd_import       *imp;
544         struct ost_body         *body;
545         int                      rc, grow, diff;
546         struct lu_fid           *fid = &oti->osi_fid;
547         ENTRY;
548
549         /* don't precreate new objects till OST healthy and has free space */
550         if (unlikely(d->opd_pre_status)) {
551                 CDEBUG(D_INFO, "%s: don't send new precreate: rc = %d\n",
552                        d->opd_obd->obd_name, d->opd_pre_status);
553                 RETURN(0);
554         }
555
556         /*
557          * if not connection/initialization is compeleted, ignore
558          */
559         imp = d->opd_obd->u.cli.cl_import;
560         LASSERT(imp);
561
562         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
563         if (req == NULL)
564                 RETURN(-ENOMEM);
565         req->rq_request_portal = OST_CREATE_PORTAL;
566         /* we should not resend create request - anyway we will have delorphan
567          * and kill these objects */
568         req->rq_no_delay = req->rq_no_resend = 1;
569
570         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
571         if (rc) {
572                 ptlrpc_request_free(req);
573                 RETURN(rc);
574         }
575
576         spin_lock(&d->opd_pre_lock);
577         if (d->opd_pre_grow_count > d->opd_pre_max_grow_count / 2)
578                 d->opd_pre_grow_count = d->opd_pre_max_grow_count / 2;
579         grow = d->opd_pre_grow_count;
580         spin_unlock(&d->opd_pre_lock);
581
582         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
583         LASSERT(body);
584
585         *fid = d->opd_pre_last_created_fid;
586         rc = osp_precreate_fids(env, d, fid, &grow);
587         if (rc == 1) {
588                 /* Current seq has been used up*/
589                 if (!osp_is_fid_client(d)) {
590                         osp_pre_update_status(d, -ENOSPC);
591                         rc = -ENOSPC;
592                 }
593                 wake_up(&d->opd_pre_waitq);
594                 GOTO(out_req, rc);
595         }
596
597         if (!osp_is_fid_client(d)) {
598                 /* Non-FID client will always send seq 0 because of
599                  * compatiblity */
600                 LASSERTF(fid_is_idif(fid), "Invalid fid "DFID"\n", PFID(fid));
601                 fid->f_seq = 0;
602         }
603
604         fid_to_ostid(fid, &body->oa.o_oi);
605         body->oa.o_valid = OBD_MD_FLGROUP;
606
607         ptlrpc_request_set_replen(req);
608
609         rc = ptlrpc_queue_wait(req);
610         if (rc) {
611                 CERROR("%s: can't precreate: rc = %d\n", d->opd_obd->obd_name,
612                        rc);
613                 GOTO(out_req, rc);
614         }
615         LASSERT(req->rq_transno == 0);
616
617         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
618         if (body == NULL)
619                 GOTO(out_req, rc = -EPROTO);
620
621         ostid_to_fid(fid, &body->oa.o_oi, d->opd_index);
622         if (osp_fid_diff(fid, &d->opd_pre_used_fid) <= 0) {
623                 CERROR("%s: precreate fid "DFID" < local used fid "DFID
624                        ": rc = %d\n", d->opd_obd->obd_name,
625                        PFID(fid), PFID(&d->opd_pre_used_fid), -ESTALE);
626                 GOTO(out_req, rc = -ESTALE);
627         }
628
629         diff = osp_fid_diff(fid, &d->opd_pre_last_created_fid);
630
631         spin_lock(&d->opd_pre_lock);
632         if (diff < grow) {
633                 /* the OST has not managed to create all the
634                  * objects we asked for */
635                 d->opd_pre_grow_count = max(diff, OST_MIN_PRECREATE);
636                 d->opd_pre_grow_slow = 1;
637         } else {
638                 /* the OST is able to keep up with the work,
639                  * we could consider increasing grow_count
640                  * next time if needed */
641                 d->opd_pre_grow_slow = 0;
642         }
643
644         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
645         fid_to_ostid(fid, &body->oa.o_oi);
646
647         d->opd_pre_last_created_fid = *fid;
648         spin_unlock(&d->opd_pre_lock);
649
650         CDEBUG(D_HA, "%s: current precreated pool: "DFID"-"DFID"\n",
651                d->opd_obd->obd_name, PFID(&d->opd_pre_used_fid),
652                PFID(&d->opd_pre_last_created_fid));
653 out_req:
654         /* now we can wakeup all users awaiting for objects */
655         osp_pre_update_status(d, rc);
656         wake_up(&d->opd_pre_user_waitq);
657
658         ptlrpc_req_finished(req);
659         RETURN(rc);
660 }
661
662 /**
663  * Get last precreated object from target (OST)
664  *
665  * Sends synchronous RPC to the target (OST) to learn the last precreated
666  * object. This later is used to remove all unused objects (cleanup orphan
667  * procedure). Also, the next object after one we got will be used as a
668  * starting point for the new precreates.
669  *
670  * \param[in] env       LU environment provided by the caller
671  * \param[in] d         OSP device
672  *
673  * \retval 0            on success
674  * \retval negative     negated errno on error
675  **/
676 static int osp_get_lastfid_from_ost(const struct lu_env *env,
677                                     struct osp_device *d)
678 {
679         struct ptlrpc_request   *req = NULL;
680         struct obd_import       *imp;
681         struct lu_fid           *last_fid;
682         char                    *tmp;
683         int                     rc;
684         ENTRY;
685
686         imp = d->opd_obd->u.cli.cl_import;
687         LASSERT(imp);
688
689         req = ptlrpc_request_alloc(imp, &RQF_OST_GET_INFO_LAST_FID);
690         if (req == NULL)
691                 RETURN(-ENOMEM);
692
693         req_capsule_set_size(&req->rq_pill, &RMF_GETINFO_KEY, RCL_CLIENT,
694                              sizeof(KEY_LAST_FID));
695
696         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_GET_INFO);
697         if (rc) {
698                 ptlrpc_request_free(req);
699                 RETURN(rc);
700         }
701
702         tmp = req_capsule_client_get(&req->rq_pill, &RMF_GETINFO_KEY);
703         memcpy(tmp, KEY_LAST_FID, sizeof(KEY_LAST_FID));
704
705         req->rq_no_delay = req->rq_no_resend = 1;
706         last_fid = req_capsule_client_get(&req->rq_pill, &RMF_FID);
707         fid_cpu_to_le(last_fid, &d->opd_last_used_fid);
708
709         ptlrpc_request_set_replen(req);
710
711         rc = ptlrpc_queue_wait(req);
712         if (rc) {
713                 /* bad-bad OST.. let sysadm sort this out */
714                 if (rc == -ENOTSUPP) {
715                         CERROR("%s: server does not support FID: rc = %d\n",
716                                d->opd_obd->obd_name, -ENOTSUPP);
717                 }
718                 ptlrpc_set_import_active(imp, 0);
719                 GOTO(out, rc);
720         }
721
722         last_fid = req_capsule_server_get(&req->rq_pill, &RMF_FID);
723         if (last_fid == NULL) {
724                 CERROR("%s: Got last_fid failed.\n", d->opd_obd->obd_name);
725                 GOTO(out, rc = -EPROTO);
726         }
727
728         if (!fid_is_sane(last_fid)) {
729                 CERROR("%s: Got insane last_fid "DFID"\n",
730                        d->opd_obd->obd_name, PFID(last_fid));
731                 GOTO(out, rc = -EPROTO);
732         }
733
734         /* Only update the last used fid, if the OST has objects for
735          * this sequence, i.e. fid_oid > 0 */
736         if (fid_oid(last_fid) > 0)
737                 d->opd_last_used_fid = *last_fid;
738
739         CDEBUG(D_HA, "%s: Got last_fid "DFID"\n", d->opd_obd->obd_name,
740                PFID(last_fid));
741
742 out:
743         ptlrpc_req_finished(req);
744         RETURN(rc);
745 }
746
747 /**
748  * Cleanup orphans on OST
749  *
750  * This function is called in a contex of a dedicated thread handling
751  * all the precreation suff. The function waits till local recovery
752  * is complete, then identify all the unreferenced objects (orphans)
753  * using the highest ID referenced by a local and the highest object
754  * precreated by the target. The found range is a subject to removal
755  * using specially flagged RPC. During this process OSP is marked
756  * unavailable for new objects.
757  *
758  * \param[in] env       LU environment provided by the caller
759  * \param[in] d         OSP device
760  *
761  * \retval 0            on success
762  * \retval negative     negated errno on error
763  */
764 static int osp_precreate_cleanup_orphans(struct lu_env *env,
765                                          struct osp_device *d)
766 {
767         struct osp_thread_info  *osi = osp_env_info(env);
768         struct lu_fid           *last_fid = &osi->osi_fid;
769         struct ptlrpc_request   *req = NULL;
770         struct obd_import       *imp;
771         struct ost_body         *body;
772         struct l_wait_info       lwi = { 0 };
773         int                      update_status = 0;
774         int                      rc;
775         int                      diff;
776
777         ENTRY;
778
779         /*
780          * wait for local recovery to finish, so we can cleanup orphans
781          * orphans are all objects since "last used" (assigned), but
782          * there might be objects reserved and in some cases they won't
783          * be used. we can't cleanup them till we're sure they won't be
784          * used. also can't we allow new reservations because they may
785          * end up getting orphans being cleaned up below. so we block
786          * new reservations and wait till all reserved objects either
787          * user or released.
788          */
789         spin_lock(&d->opd_pre_lock);
790         d->opd_pre_recovering = 1;
791         spin_unlock(&d->opd_pre_lock);
792         /*
793          * The locking above makes sure the opd_pre_reserved check below will
794          * catch all osp_precreate_reserve() calls who find
795          * "!opd_pre_recovering".
796          */
797         l_wait_event(d->opd_pre_waitq,
798                      (!d->opd_pre_reserved && d->opd_recovery_completed) ||
799                      !osp_precreate_running(d) || d->opd_got_disconnected,
800                      &lwi);
801         if (!osp_precreate_running(d) || d->opd_got_disconnected)
802                 GOTO(out, rc = -EAGAIN);
803
804         CDEBUG(D_HA, "%s: going to cleanup orphans since "DFID"\n",
805                d->opd_obd->obd_name, PFID(&d->opd_last_used_fid));
806
807         *last_fid = d->opd_last_used_fid;
808         /* The OSP should already get the valid seq now */
809         LASSERT(!fid_is_zero(last_fid));
810         if (fid_oid(&d->opd_last_used_fid) < 2) {
811                 /* lastfid looks strange... ask OST */
812                 rc = osp_get_lastfid_from_ost(env, d);
813                 if (rc)
814                         GOTO(out, rc);
815         }
816
817         imp = d->opd_obd->u.cli.cl_import;
818         LASSERT(imp);
819
820         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
821         if (req == NULL)
822                 GOTO(out, rc = -ENOMEM);
823
824         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
825         if (rc) {
826                 ptlrpc_request_free(req);
827                 req = NULL;
828                 GOTO(out, rc);
829         }
830
831         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
832         if (body == NULL)
833                 GOTO(out, rc = -EPROTO);
834
835         body->oa.o_flags = OBD_FL_DELORPHAN;
836         body->oa.o_valid = OBD_MD_FLFLAGS | OBD_MD_FLGROUP;
837
838         fid_to_ostid(&d->opd_last_used_fid, &body->oa.o_oi);
839
840         ptlrpc_request_set_replen(req);
841
842         /* Don't resend the delorphan req */
843         req->rq_no_resend = req->rq_no_delay = 1;
844
845         rc = ptlrpc_queue_wait(req);
846         if (rc) {
847                 update_status = 1;
848                 GOTO(out, rc);
849         }
850
851         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
852         if (body == NULL)
853                 GOTO(out, rc = -EPROTO);
854
855         /*
856          * OST provides us with id new pool starts from in body->oa.o_id
857          */
858         ostid_to_fid(last_fid, &body->oa.o_oi, d->opd_index);
859
860         spin_lock(&d->opd_pre_lock);
861         diff = osp_fid_diff(&d->opd_last_used_fid, last_fid);
862         if (diff > 0) {
863                 d->opd_pre_grow_count = OST_MIN_PRECREATE + diff;
864                 d->opd_pre_last_created_fid = d->opd_last_used_fid;
865         } else {
866                 d->opd_pre_grow_count = OST_MIN_PRECREATE;
867                 d->opd_pre_last_created_fid = *last_fid;
868         }
869         /*
870          * This empties the pre-creation pool and effectively blocks any new
871          * reservations.
872          */
873         LASSERT(fid_oid(&d->opd_pre_last_created_fid) <=
874                 LUSTRE_DATA_SEQ_MAX_WIDTH);
875         d->opd_pre_used_fid = d->opd_pre_last_created_fid;
876         d->opd_pre_grow_slow = 0;
877         spin_unlock(&d->opd_pre_lock);
878
879         CDEBUG(D_HA, "%s: Got last_id "DFID" from OST, last_created "DFID
880                "last_used is "DFID"\n", d->opd_obd->obd_name, PFID(last_fid),
881                PFID(&d->opd_pre_last_created_fid), PFID(&d->opd_last_used_fid));
882 out:
883         if (req)
884                 ptlrpc_req_finished(req);
885
886         spin_lock(&d->opd_pre_lock);
887         d->opd_pre_recovering = 0;
888         spin_unlock(&d->opd_pre_lock);
889
890         /*
891          * If rc is zero, the pre-creation window should have been emptied.
892          * Since waking up the herd would be useless without pre-created
893          * objects, we defer the signal to osp_precreate_send() in that case.
894          */
895         if (rc != 0) {
896                 if (update_status) {
897                         CERROR("%s: cannot cleanup orphans: rc = %d\n",
898                                d->opd_obd->obd_name, rc);
899                         /* we can't proceed from here, OST seem to
900                          * be in a bad shape, better to wait for
901                          * a new instance of the server and repeat
902                          * from the beginning. notify possible waiters
903                          * this OSP isn't quite functional yet */
904                         osp_pre_update_status(d, rc);
905                 } else {
906                         wake_up(&d->opd_pre_user_waitq);
907                 }
908         }
909
910         RETURN(rc);
911 }
912
913 /**
914  * Update precreate status using statfs data
915  *
916  * The function decides whether this OSP should be used for new objects.
917  * IOW, whether this OST is used up or has some free space. Cached statfs
918  * data is used to make this decision. If the latest result of statfs
919  * request (rc argument) is not success, then just mark OSP unavailable
920  * right away.
921
922  * Add a bit of hysteresis so this flag isn't continually flapping,
923  * and ensure that new files don't get extremely fragmented due to
924  * only a small amount of available space in the filesystem.
925  * We want to set the NOSPC flag when there is less than ~0.1% free
926  * and clear it when there is at least ~0.2% free space, so:
927  *                   avail < ~0.1% max          max = avail + used
928  *            1025 * avail < avail + used       used = blocks - free
929  *            1024 * avail < used
930  *            1024 * avail < blocks - free
931  *                   avail < ((blocks - free) >> 10)
932  *
933  * On very large disk, say 16TB 0.1% will be 16 GB. We don't want to
934  * lose that amount of space so in those cases we report no space left
935  * if their is less than 1 GB left.
936  * the function updates current precreation status used: functional or not
937  *
938  * \param[in] d         OSP device
939  * \param[in] rc        new precreate status for device \a d
940  *
941  * \retval 0            on success
942  * \retval negative     negated errno on error
943  */
944 void osp_pre_update_status(struct osp_device *d, int rc)
945 {
946         struct obd_statfs       *msfs = &d->opd_statfs;
947         int                      old = d->opd_pre_status;
948         __u64                    used;
949
950         d->opd_pre_status = rc;
951         if (rc)
952                 goto out;
953
954         if (likely(msfs->os_type)) {
955                 used = min_t(__u64, (msfs->os_blocks - msfs->os_bfree) >> 10,
956                                     1 << 30);
957                 if ((msfs->os_ffree < 32) || (msfs->os_bavail < used)) {
958                         d->opd_pre_status = -ENOSPC;
959                         if (old != -ENOSPC)
960                                 CDEBUG(D_INFO, "%s: status: "LPU64" blocks, "
961                                        LPU64" free, "LPU64" used, "LPU64" "
962                                        "avail -> %d: rc = %d\n",
963                                        d->opd_obd->obd_name, msfs->os_blocks,
964                                        msfs->os_bfree, used, msfs->os_bavail,
965                                        d->opd_pre_status, rc);
966                         CDEBUG(D_INFO,
967                                "non-commited changes: %lu, in progress: %u\n",
968                                d->opd_syn_changes, d->opd_syn_rpc_in_progress);
969                 } else if (old == -ENOSPC) {
970                         d->opd_pre_status = 0;
971                         spin_lock(&d->opd_pre_lock);
972                         d->opd_pre_grow_slow = 0;
973                         d->opd_pre_grow_count = OST_MIN_PRECREATE;
974                         spin_unlock(&d->opd_pre_lock);
975                         wake_up(&d->opd_pre_waitq);
976                         CDEBUG(D_INFO, "%s: no space: "LPU64" blocks, "LPU64
977                                " free, "LPU64" used, "LPU64" avail -> %d: "
978                                "rc = %d\n", d->opd_obd->obd_name,
979                                msfs->os_blocks, msfs->os_bfree, used,
980                                msfs->os_bavail, d->opd_pre_status, rc);
981                 }
982         }
983
984 out:
985         wake_up(&d->opd_pre_user_waitq);
986 }
987
988 /**
989  * Initialize FID for precreation
990  *
991  * For a just created new target, a new sequence should be taken.
992  * The function checks there is no IDIF in use (if the target was
993  * added with the older version of Lustre), then requests a new
994  * sequence from FLDB using the regular protocol. Then this new
995  * sequence is stored on a persisten storage synchronously to prevent
996  * possible object leakage (for the detail see the description for
997  * osp_precreate_rollover_new_seq()).
998  *
999  * \param[in] osp       OSP device
1000  *
1001  * \retval 0            on success
1002  * \retval negative     negated errno on error
1003  */
1004 int osp_init_pre_fid(struct osp_device *osp)
1005 {
1006         struct lu_env           env;
1007         struct osp_thread_info  *osi;
1008         struct lu_client_seq    *cli_seq;
1009         struct lu_fid           *last_fid;
1010         int                     rc;
1011         ENTRY;
1012
1013         LASSERT(osp->opd_pre != NULL);
1014
1015         /* Return if last_used fid has been initialized */
1016         if (!fid_is_zero(&osp->opd_last_used_fid))
1017                 RETURN(0);
1018
1019         rc = lu_env_init(&env, osp->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1020         if (rc) {
1021                 CERROR("%s: init env error: rc = %d\n",
1022                        osp->opd_obd->obd_name, rc);
1023                 RETURN(rc);
1024         }
1025
1026         osi = osp_env_info(&env);
1027         last_fid = &osi->osi_fid;
1028         fid_zero(last_fid);
1029         /* For a freshed fs, it will allocate a new sequence first */
1030         if (osp_is_fid_client(osp) && osp->opd_group != 0) {
1031                 cli_seq = osp->opd_obd->u.cli.cl_seq;
1032                 rc = seq_client_get_seq(&env, cli_seq, &last_fid->f_seq);
1033                 if (rc != 0) {
1034                         CERROR("%s: alloc fid error: rc = %d\n",
1035                                osp->opd_obd->obd_name, rc);
1036                         GOTO(out, rc);
1037                 }
1038         } else {
1039                 last_fid->f_seq = fid_idif_seq(0, osp->opd_index);
1040         }
1041         last_fid->f_oid = 1;
1042         last_fid->f_ver = 0;
1043
1044         spin_lock(&osp->opd_pre_lock);
1045         osp->opd_last_used_fid = *last_fid;
1046         osp->opd_pre_used_fid = *last_fid;
1047         osp->opd_pre_last_created_fid = *last_fid;
1048         spin_unlock(&osp->opd_pre_lock);
1049         rc = osp_write_last_oid_seq_files(&env, osp, last_fid, 1);
1050         if (rc != 0) {
1051                 CERROR("%s: write fid error: rc = %d\n",
1052                        osp->opd_obd->obd_name, rc);
1053                 GOTO(out, rc);
1054         }
1055 out:
1056         lu_env_fini(&env);
1057         RETURN(rc);
1058 }
1059
1060 /**
1061  * The core of precreate functionality
1062  *
1063  * The function implements the main precreation loop. Basically it
1064  * involves connecting to the target, precerate FID initialization,
1065  * identifying and removing orphans, then serving precreation. As
1066  * part of the latter, the thread is responsible for statfs data
1067  * updates. The precreation is mostly driven by another threads
1068  * asking for new OST objects - those askers wake the thread when
1069  * the number of precreated objects reach low watermark.
1070  * After a disconnect, the sequence above repeats. This is keep going
1071  * until the thread is requested to stop.
1072  *
1073  * \param[in] _arg      private data the thread (OSP device to handle)
1074  *
1075  * \retval 0            on success
1076  * \retval negative     negated errno on error
1077  */
1078 static int osp_precreate_thread(void *_arg)
1079 {
1080         struct osp_device       *d = _arg;
1081         struct ptlrpc_thread    *thread = &d->opd_pre_thread;
1082         struct l_wait_info       lwi = { 0 };
1083         struct lu_env            env;
1084         int                      rc;
1085
1086         ENTRY;
1087
1088         rc = lu_env_init(&env, d->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1089         if (rc) {
1090                 CERROR("%s: init env error: rc = %d\n", d->opd_obd->obd_name,
1091                        rc);
1092                 RETURN(rc);
1093         }
1094
1095         spin_lock(&d->opd_pre_lock);
1096         thread->t_flags = SVC_RUNNING;
1097         spin_unlock(&d->opd_pre_lock);
1098         wake_up(&thread->t_ctl_waitq);
1099
1100         while (osp_precreate_running(d)) {
1101                 /*
1102                  * need to be connected to OST
1103                  */
1104                 while (osp_precreate_running(d)) {
1105                         l_wait_event(d->opd_pre_waitq,
1106                                      !osp_precreate_running(d) ||
1107                                      d->opd_new_connection,
1108                                      &lwi);
1109
1110                         if (!d->opd_new_connection)
1111                                 continue;
1112
1113                         d->opd_new_connection = 0;
1114                         d->opd_got_disconnected = 0;
1115                         break;
1116                 }
1117
1118                 if (!osp_precreate_running(d))
1119                         break;
1120
1121                 LASSERT(d->opd_obd->u.cli.cl_seq != NULL);
1122                 /* Sigh, fid client is not ready yet */
1123                 if (d->opd_obd->u.cli.cl_seq->lcs_exp == NULL)
1124                         continue;
1125
1126                 /* Init fid for osp_precreate if necessary */
1127                 rc = osp_init_pre_fid(d);
1128                 if (rc != 0) {
1129                         class_export_put(d->opd_exp);
1130                         d->opd_obd->u.cli.cl_seq->lcs_exp = NULL;
1131                         CERROR("%s: init pre fid error: rc = %d\n",
1132                                d->opd_obd->obd_name, rc);
1133                         continue;
1134                 }
1135
1136                 osp_statfs_update(d);
1137
1138                 /*
1139                  * Clean up orphans or recreate missing objects.
1140                  */
1141                 rc = osp_precreate_cleanup_orphans(&env, d);
1142                 if (rc != 0)
1143                         continue;
1144                 /*
1145                  * connected, can handle precreates now
1146                  */
1147                 while (osp_precreate_running(d)) {
1148                         l_wait_event(d->opd_pre_waitq,
1149                                      !osp_precreate_running(d) ||
1150                                      osp_precreate_near_empty(&env, d) ||
1151                                      osp_statfs_need_update(d) ||
1152                                      d->opd_got_disconnected, &lwi);
1153
1154                         if (!osp_precreate_running(d))
1155                                 break;
1156
1157                         /* something happened to the connection
1158                          * have to start from the beginning */
1159                         if (d->opd_got_disconnected)
1160                                 break;
1161
1162                         if (osp_statfs_need_update(d))
1163                                 osp_statfs_update(d);
1164
1165                         /* To avoid handling different seq in precreate/orphan
1166                          * cleanup, it will hold precreate until current seq is
1167                          * used up. */
1168                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1169                             !osp_create_end_seq(&env, d)))
1170                                 continue;
1171
1172                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1173                                      osp_create_end_seq(&env, d))) {
1174                                 LCONSOLE_INFO("%s:"LPX64" is used up."
1175                                               " Update to new seq\n",
1176                                               d->opd_obd->obd_name,
1177                                          fid_seq(&d->opd_pre_last_created_fid));
1178                                 rc = osp_precreate_rollover_new_seq(&env, d);
1179                                 if (rc)
1180                                         continue;
1181                         }
1182
1183                         if (osp_precreate_near_empty(&env, d)) {
1184                                 rc = osp_precreate_send(&env, d);
1185                                 /* osp_precreate_send() sets opd_pre_status
1186                                  * in case of error, that prevent the using of
1187                                  * failed device. */
1188                                 if (rc < 0 && rc != -ENOSPC &&
1189                                     rc != -ETIMEDOUT && rc != -ENOTCONN)
1190                                         CERROR("%s: cannot precreate objects:"
1191                                                " rc = %d\n",
1192                                                d->opd_obd->obd_name, rc);
1193                         }
1194                 }
1195         }
1196
1197         thread->t_flags = SVC_STOPPED;
1198         lu_env_fini(&env);
1199         wake_up(&thread->t_ctl_waitq);
1200
1201         RETURN(0);
1202 }
1203
1204 /**
1205  * Check when to stop to wait for precreate objects.
1206  *
1207  * The caller wanting a new OST object can't wait undefinitely. The
1208  * function checks for few conditions including available new OST
1209  * objects, disconnected OST, lack of space with no pending destroys,
1210  * etc. IOW, it checks whether the current OSP state is good to keep
1211  * waiting or it's better to give up.
1212  *
1213  * \param[in] env       LU environment provided by the caller
1214  * \param[in] d         OSP device
1215  *
1216  * \retval              0 - keep waiting, 1 - no luck
1217  */
1218 static int osp_precreate_ready_condition(const struct lu_env *env,
1219                                          struct osp_device *d)
1220 {
1221         if (d->opd_pre_recovering)
1222                 return 0;
1223
1224         /* ready if got enough precreated objects */
1225         /* we need to wait for others (opd_pre_reserved) and our object (+1) */
1226         if (d->opd_pre_reserved + 1 < osp_objs_precreated(env, d))
1227                 return 1;
1228
1229         /* ready if OST reported no space and no destroys in progress */
1230         if (d->opd_syn_changes + d->opd_syn_rpc_in_progress == 0 &&
1231             d->opd_pre_status == -ENOSPC)
1232                 return 1;
1233
1234         /* Bail out I/O fails to OST */
1235         if (d->opd_pre_status != 0 &&
1236             d->opd_pre_status != -EAGAIN &&
1237             d->opd_pre_status != -ENODEV &&
1238             d->opd_pre_status != -ENOSPC) {
1239                 /* DEBUG LU-3230 */
1240                 if (d->opd_pre_status != -EIO)
1241                         CERROR("%s: precreate failed opd_pre_status %d\n",
1242                                d->opd_obd->obd_name, d->opd_pre_status);
1243                 return 1;
1244         }
1245
1246         return 0;
1247 }
1248
1249 static int osp_precreate_timeout_condition(void *data)
1250 {
1251         struct osp_device *d = data;
1252
1253         CDEBUG(D_HA, "%s: slow creates, last="DFID", next="DFID", "
1254               "reserved="LPU64", syn_changes=%lu, "
1255               "syn_rpc_in_progress=%d, status=%d\n",
1256               d->opd_obd->obd_name, PFID(&d->opd_pre_last_created_fid),
1257               PFID(&d->opd_pre_used_fid), d->opd_pre_reserved,
1258               d->opd_syn_changes, d->opd_syn_rpc_in_progress,
1259               d->opd_pre_status);
1260
1261         return 1;
1262 }
1263
1264 /**
1265  * Reserve object in precreate pool
1266  *
1267  * When the caller wants to create a new object on this target (target
1268  * represented by the given OSP), it should declare this intention using
1269  * a regular ->dt_declare_create() OSD API method. Then OSP will be trying
1270  * to reserve an object in the existing precreated pool or wait up to
1271  * obd_timeout for the available object to appear in the pool (a dedicated
1272  * thread will be doing real precreation in background). The object can be
1273  * consumed later with osp_precreate_get_fid() or be released with call to
1274  * lu_object_put(). Notice the function doesn't reserve a specific ID, just
1275  * some ID. The actual ID assignment happen in osp_precreate_get_fid().
1276  * If the space on the target is short and there is a pending object destroy,
1277  * then the function forces local commit to speedup space release (see
1278  * osp_sync.c for the details).
1279  *
1280  * \param[in] env       LU environment provided by the caller
1281  * \param[in] d         OSP device
1282  *
1283  * \retval              0 on success
1284  * \retval              -ENOSPC when no space on OST
1285  * \retval              -EAGAIN try later, slow precreation in progress
1286  * \retval              -EIO when no access to OST
1287  */
1288 int osp_precreate_reserve(const struct lu_env *env, struct osp_device *d)
1289 {
1290         struct l_wait_info       lwi;
1291         cfs_time_t               expire = cfs_time_shift(obd_timeout);
1292         int                      precreated, rc;
1293
1294         ENTRY;
1295
1296         LASSERTF(osp_objs_precreated(env, d) >= 0, "Last created FID "DFID
1297                  "Next FID "DFID"\n", PFID(&d->opd_pre_last_created_fid),
1298                  PFID(&d->opd_pre_used_fid));
1299
1300         /*
1301          * wait till:
1302          *  - preallocation is done
1303          *  - no free space expected soon
1304          *  - can't connect to OST for too long (obd_timeout)
1305          *  - OST can allocate fid sequence.
1306          */
1307         while ((rc = d->opd_pre_status) == 0 || rc == -ENOSPC ||
1308                 rc == -ENODEV || rc == -EAGAIN || rc == -ENOTCONN) {
1309
1310                 /*
1311                  * increase number of precreations
1312                  */
1313                 precreated = osp_objs_precreated(env, d);
1314                 if (d->opd_pre_grow_count < d->opd_pre_max_grow_count &&
1315                     d->opd_pre_grow_slow == 0 &&
1316                     precreated <= (d->opd_pre_grow_count / 4 + 1)) {
1317                         spin_lock(&d->opd_pre_lock);
1318                         d->opd_pre_grow_slow = 1;
1319                         d->opd_pre_grow_count *= 2;
1320                         spin_unlock(&d->opd_pre_lock);
1321                 }
1322
1323                 spin_lock(&d->opd_pre_lock);
1324                 precreated = osp_objs_precreated(env, d);
1325                 if (precreated > d->opd_pre_reserved &&
1326                     !d->opd_pre_recovering) {
1327                         d->opd_pre_reserved++;
1328                         spin_unlock(&d->opd_pre_lock);
1329                         rc = 0;
1330
1331                         /* XXX: don't wake up if precreation is in progress */
1332                         if (osp_precreate_near_empty_nolock(env, d) &&
1333                            !osp_precreate_end_seq_nolock(env, d))
1334                                 wake_up(&d->opd_pre_waitq);
1335
1336                         break;
1337                 }
1338                 spin_unlock(&d->opd_pre_lock);
1339
1340                 /*
1341                  * all precreated objects have been used and no-space
1342                  * status leave us no chance to succeed very soon
1343                  * but if there is destroy in progress, then we should
1344                  * wait till that is done - some space might be released
1345                  */
1346                 if (unlikely(rc == -ENOSPC)) {
1347                         if (d->opd_syn_changes) {
1348                                 /* force local commit to release space */
1349                                 dt_commit_async(env, d->opd_storage);
1350                         }
1351                         if (d->opd_syn_rpc_in_progress) {
1352                                 /* just wait till destroys are done */
1353                                 /* see l_wait_even() few lines below */
1354                         }
1355                         if (d->opd_syn_changes +
1356                             d->opd_syn_rpc_in_progress == 0) {
1357                                 /* no hope for free space */
1358                                 break;
1359                         }
1360                 }
1361
1362                 /* XXX: don't wake up if precreation is in progress */
1363                 wake_up(&d->opd_pre_waitq);
1364
1365                 lwi = LWI_TIMEOUT(expire - cfs_time_current(),
1366                                 osp_precreate_timeout_condition, d);
1367                 if (cfs_time_aftereq(cfs_time_current(), expire)) {
1368                         rc = -ETIMEDOUT;
1369                         break;
1370                 }
1371
1372                 l_wait_event(d->opd_pre_user_waitq,
1373                              osp_precreate_ready_condition(env, d), &lwi);
1374         }
1375
1376         RETURN(rc);
1377 }
1378
1379 /**
1380  * Get a FID from precreation pool
1381  *
1382  * The function is a companion for osp_precreate_reserve() - it assigns
1383  * a specific FID from the precreate. The function should be called only
1384  * if the call to osp_precreate_reserve() was successful. The function
1385  * updates a local storage to remember the highest object ID referenced
1386  * by the node in the given sequence.
1387  *
1388  * A very importan details: this is supposed to be called once the
1389  * transaction is started, so on-disk update will be atomic with the
1390  * data (like LOVEA) refering this object. Then the object won't be leaked:
1391  * either it's referenced by the committed transaction or it's a subject
1392  * to the orphan cleanup procedure.
1393  *
1394  * \param[in] env       LU environment provided by the caller
1395  * \param[in] d         OSP device
1396  * \param[out] fid      generated FID
1397  *
1398  * \retval 0            on success
1399  * \retval negative     negated errno on error
1400  */
1401 int osp_precreate_get_fid(const struct lu_env *env, struct osp_device *d,
1402                           struct lu_fid *fid)
1403 {
1404         /* grab next id from the pool */
1405         spin_lock(&d->opd_pre_lock);
1406
1407         LASSERTF(osp_fid_diff(&d->opd_pre_used_fid,
1408                              &d->opd_pre_last_created_fid) < 0,
1409                  "next fid "DFID" last created fid "DFID"\n",
1410                  PFID(&d->opd_pre_used_fid),
1411                  PFID(&d->opd_pre_last_created_fid));
1412
1413         d->opd_pre_used_fid.f_oid++;
1414         memcpy(fid, &d->opd_pre_used_fid, sizeof(*fid));
1415         d->opd_pre_reserved--;
1416         /*
1417          * last_used_id must be changed along with getting new id otherwise
1418          * we might miscalculate gap causing object loss or leak
1419          */
1420         osp_update_last_fid(d, fid);
1421         spin_unlock(&d->opd_pre_lock);
1422
1423         /*
1424          * probably main thread suspended orphan cleanup till
1425          * all reservations are released, see comment in
1426          * osp_precreate_thread() just before orphan cleanup
1427          */
1428         if (unlikely(d->opd_pre_reserved == 0 && d->opd_pre_status))
1429                 wake_up(&d->opd_pre_waitq);
1430
1431         return 0;
1432 }
1433
1434 /*
1435  * Set size regular attribute on an object
1436  *
1437  * When a striping is created late, it's possible that size is already
1438  * initialized on the file. Then the new striping should inherit size
1439  * from the file. The function sets size on the object using the regular
1440  * protocol (OST_PUNCH).
1441  * XXX: should be re-implemented using OUT ?
1442  *
1443  * \param[in] env       LU environment provided by the caller
1444  * \param[in] dt        object
1445  * \param[in] size      size to set.
1446  *
1447  * \retval 0            on success
1448  * \retval negative     negated errno on error
1449  */
1450 int osp_object_truncate(const struct lu_env *env, struct dt_object *dt,
1451                         __u64 size)
1452 {
1453         struct osp_device       *d = lu2osp_dev(dt->do_lu.lo_dev);
1454         struct ptlrpc_request   *req = NULL;
1455         struct obd_import       *imp;
1456         struct ost_body         *body;
1457         struct obdo             *oa = NULL;
1458         int                      rc;
1459
1460         ENTRY;
1461
1462         imp = d->opd_obd->u.cli.cl_import;
1463         LASSERT(imp);
1464
1465         req = ptlrpc_request_alloc(imp, &RQF_OST_PUNCH);
1466         if (req == NULL)
1467                 RETURN(-ENOMEM);
1468
1469         /* XXX: capa support? */
1470         /* osc_set_capa_size(req, &RMF_CAPA1, capa); */
1471         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_PUNCH);
1472         if (rc) {
1473                 ptlrpc_request_free(req);
1474                 RETURN(rc);
1475         }
1476
1477         /*
1478          * XXX: decide how do we do here with resend
1479          * if we don't resend, then client may see wrong file size
1480          * if we do resend, then MDS thread can get stuck for quite long
1481          */
1482         req->rq_no_resend = req->rq_no_delay = 1;
1483
1484         req->rq_request_portal = OST_IO_PORTAL; /* bug 7198 */
1485         ptlrpc_at_set_req_timeout(req);
1486
1487         OBD_ALLOC_PTR(oa);
1488         if (oa == NULL)
1489                 GOTO(out, rc = -ENOMEM);
1490
1491         rc = fid_to_ostid(lu_object_fid(&dt->do_lu), &oa->o_oi);
1492         LASSERT(rc == 0);
1493         oa->o_size = size;
1494         oa->o_blocks = OBD_OBJECT_EOF;
1495         oa->o_valid = OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
1496                       OBD_MD_FLID | OBD_MD_FLGROUP;
1497
1498         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
1499         LASSERT(body);
1500         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa, oa);
1501
1502         /* XXX: capa support? */
1503         /* osc_pack_capa(req, body, capa); */
1504
1505         ptlrpc_request_set_replen(req);
1506
1507         rc = ptlrpc_queue_wait(req);
1508         if (rc)
1509                 CERROR("can't punch object: %d\n", rc);
1510 out:
1511         ptlrpc_req_finished(req);
1512         if (oa)
1513                 OBD_FREE_PTR(oa);
1514         RETURN(rc);
1515 }
1516
1517 /**
1518  * Initialize precreation functionality of OSP
1519  *
1520  * Prepares all the internal structures and starts the precreate thread
1521  *
1522  * \param[in] d         OSP device
1523  *
1524  * \retval 0            on success
1525  * \retval negative     negated errno on error
1526  */
1527 int osp_init_precreate(struct osp_device *d)
1528 {
1529         struct l_wait_info       lwi = { 0 };
1530         struct task_struct              *task;
1531
1532         ENTRY;
1533
1534         OBD_ALLOC_PTR(d->opd_pre);
1535         if (d->opd_pre == NULL)
1536                 RETURN(-ENOMEM);
1537
1538         /* initially precreation isn't ready */
1539         d->opd_pre_status = -EAGAIN;
1540         fid_zero(&d->opd_pre_used_fid);
1541         d->opd_pre_used_fid.f_oid = 1;
1542         fid_zero(&d->opd_pre_last_created_fid);
1543         d->opd_pre_last_created_fid.f_oid = 1;
1544         d->opd_pre_reserved = 0;
1545         d->opd_got_disconnected = 1;
1546         d->opd_pre_grow_slow = 0;
1547         d->opd_pre_grow_count = OST_MIN_PRECREATE;
1548         d->opd_pre_min_grow_count = OST_MIN_PRECREATE;
1549         d->opd_pre_max_grow_count = OST_MAX_PRECREATE;
1550
1551         spin_lock_init(&d->opd_pre_lock);
1552         init_waitqueue_head(&d->opd_pre_waitq);
1553         init_waitqueue_head(&d->opd_pre_user_waitq);
1554         init_waitqueue_head(&d->opd_pre_thread.t_ctl_waitq);
1555
1556         /*
1557          * Initialize statfs-related things
1558          */
1559         d->opd_statfs_maxage = 5; /* default update interval */
1560         d->opd_statfs_fresh_till = cfs_time_shift(-1000);
1561         CDEBUG(D_OTHER, "current %llu, fresh till %llu\n",
1562                (unsigned long long)cfs_time_current(),
1563                (unsigned long long)d->opd_statfs_fresh_till);
1564         cfs_timer_init(&d->opd_statfs_timer, osp_statfs_timer_cb, d);
1565
1566         /*
1567          * start thread handling precreation and statfs updates
1568          */
1569         task = kthread_run(osp_precreate_thread, d,
1570                            "osp-pre-%u-%u", d->opd_index, d->opd_group);
1571         if (IS_ERR(task)) {
1572                 CERROR("can't start precreate thread %ld\n", PTR_ERR(task));
1573                 RETURN(PTR_ERR(task));
1574         }
1575
1576         l_wait_event(d->opd_pre_thread.t_ctl_waitq,
1577                      osp_precreate_running(d) || osp_precreate_stopped(d),
1578                      &lwi);
1579
1580         RETURN(0);
1581 }
1582
1583 /**
1584  * Finish precreate functionality of OSP
1585  *
1586  *
1587  * Asks all the activity (the thread, update timer) to stop, then
1588  * wait till that is done.
1589  *
1590  * \param[in] d         OSP device
1591  */
1592 void osp_precreate_fini(struct osp_device *d)
1593 {
1594         struct ptlrpc_thread *thread;
1595
1596         ENTRY;
1597
1598         cfs_timer_disarm(&d->opd_statfs_timer);
1599
1600         if (d->opd_pre == NULL)
1601                 RETURN_EXIT;
1602
1603         thread = &d->opd_pre_thread;
1604
1605         thread->t_flags = SVC_STOPPING;
1606         wake_up(&d->opd_pre_waitq);
1607
1608         wait_event(thread->t_ctl_waitq, thread->t_flags & SVC_STOPPED);
1609
1610         OBD_FREE_PTR(d->opd_pre);
1611         d->opd_pre = NULL;
1612
1613         EXIT;
1614 }
1615