Whamcloud - gitweb
LU-10383 hsm: consolidate CDT restore handle handling
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2017, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_export.h>
44 #include <obd.h>
45 #include <lprocfs_status.h>
46 #include <lustre_log.h>
47 #include <lustre_kernelcomm.h>
48 #include "mdt_internal.h"
49
50 static struct lprocfs_vars lprocfs_mdt_hsm_vars[];
51
52 /**
53  * get obj and HSM attributes on a fid
54  * \param mti [IN] context
55  * \param fid [IN] object fid
56  * \param hsm [OUT] HSM meta data
57  * \retval obj or error (-ENOENT if not found)
58  */
59 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
60                                       const struct lu_fid *fid,
61                                       struct md_hsm *hsm)
62 {
63         struct md_attr          *ma;
64         struct mdt_object       *obj;
65         int                      rc;
66         ENTRY;
67
68         ma = &mti->mti_attr;
69         ma->ma_need = MA_HSM;
70         ma->ma_valid = 0;
71
72         /* find object by FID */
73         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
74         if (IS_ERR(obj))
75                 RETURN(obj);
76
77         if (!mdt_object_exists(obj)) {
78                 /* no more object */
79                 mdt_object_put(mti->mti_env, obj);
80                 RETURN(ERR_PTR(-ENOENT));
81         }
82
83         rc = mdt_attr_get_complex(mti, obj, ma);
84         if (rc) {
85                 mdt_object_put(mti->mti_env, obj);
86                 RETURN(ERR_PTR(rc));
87         }
88
89         if (ma->ma_valid & MA_HSM)
90                 *hsm = ma->ma_hsm;
91         else
92                 memset(hsm, 0, sizeof(*hsm));
93         ma->ma_valid = 0;
94         RETURN(obj);
95 }
96
97 void mdt_hsm_dump_hal(int level, const char *prefix,
98                       struct hsm_action_list *hal)
99 {
100         int                      i, sz;
101         struct hsm_action_item  *hai;
102         char                     buf[12];
103
104         CDEBUG(level, "%s: HAL header: version %X count %d compound %#llx"
105                       " archive_id %d flags %#llx\n",
106                prefix, hal->hal_version, hal->hal_count,
107                hal->hal_compound_id, hal->hal_archive_id, hal->hal_flags);
108
109         hai = hai_first(hal);
110         for (i = 0; i < hal->hal_count; i++) {
111                 sz = hai->hai_len - sizeof(*hai);
112                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
113                        " compound/cookie=%#llx/%#llx"
114                        " action=%s extent=%#llx-%#llx gid=%#llx"
115                        " datalen=%d data=[%s]\n",
116                        prefix, i,
117                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
118                        hal->hal_compound_id, hai->hai_cookie,
119                        hsm_copytool_action2name(hai->hai_action),
120                        hai->hai_extent.offset,
121                        hai->hai_extent.length,
122                        hai->hai_gid, sz,
123                        hai_dump_data_field(hai, buf, sizeof(buf)));
124                 hai = hai_next(hai);
125         }
126 }
127
128 /**
129  * data passed to llog_cat_process() callback
130  * to scan requests and take actions
131  */
132 struct hsm_scan_request {
133         int                      hal_sz;
134         int                      hal_used_sz;
135         struct hsm_action_list  *hal;
136 };
137
138 struct hsm_scan_data {
139         struct mdt_thread_info          *mti;
140         char                             fs_name[MTI_NAME_MAXLEN+1];
141         /* are we scanning the logs for housekeeping, or just looking
142          * for new work?
143          */
144         bool                             housekeeping;
145         /* request to be send to agents */
146         int                              max_requests;  /** vector size */
147         int                              request_cnt;   /** used count */
148         struct hsm_scan_request         *request;
149 };
150
151 struct hsm_thread_data {
152         struct mdt_thread_info  *cdt_mti;
153         struct hsm_scan_request *request;
154 };
155
156 static int mdt_cdt_waiting_cb(const struct lu_env *env,
157                               struct mdt_device *mdt,
158                               struct llog_handle *llh,
159                               struct llog_agent_req_rec *larr,
160                               struct hsm_scan_data *hsd)
161 {
162         struct coordinator *cdt = &mdt->mdt_coordinator;
163         struct hsm_scan_request *request;
164         struct hsm_action_item *hai;
165         int i;
166
167         /* Are agents full? */
168         if (atomic_read(&cdt->cdt_request_count) >= cdt->cdt_max_requests)
169                 RETURN(0);
170
171         /* first search whether the request is found in the list we
172          * have built. */
173         request = NULL;
174         for (i = 0; i < hsd->request_cnt; i++) {
175                 if (hsd->request[i].hal->hal_compound_id ==
176                     larr->arr_compound_id) {
177                         request = &hsd->request[i];
178                         break;
179                 }
180         }
181
182         if (!request) {
183                 struct hsm_action_list *hal;
184
185                 if (hsd->request_cnt == hsd->max_requests) {
186                         if (!hsd->housekeeping) {
187                                 /* The request array is full, stop
188                                  * here. There might be more known
189                                  * requests that could be merged, but
190                                  * this avoid analyzing too many llogs
191                                  * for minor gains. */
192                                 RETURN(LLOG_PROC_BREAK);
193                         } else {
194                                 /* Unknown request and no more room
195                                  * for a new request. Continue to scan
196                                  * to find other entries for already
197                                  * existing requests. */
198                                 RETURN(0);
199                         }
200                 }
201
202                 request = &hsd->request[hsd->request_cnt];
203
204                 /* allocates hai vector size just needs to be large
205                  * enough */
206                 request->hal_sz = sizeof(*request->hal) +
207                         cfs_size_round(MTI_NAME_MAXLEN + 1) +
208                         2 * cfs_size_round(larr->arr_hai.hai_len);
209                 OBD_ALLOC(hal, request->hal_sz);
210                 if (!hal)
211                         RETURN(-ENOMEM);
212
213                 hal->hal_version = HAL_VERSION;
214                 strlcpy(hal->hal_fsname, hsd->fs_name, MTI_NAME_MAXLEN + 1);
215                 hal->hal_compound_id = larr->arr_compound_id;
216                 hal->hal_archive_id = larr->arr_archive_id;
217                 hal->hal_flags = larr->arr_flags;
218                 hal->hal_count = 0;
219                 request->hal_used_sz = hal_size(hal);
220                 request->hal = hal;
221                 hsd->request_cnt++;
222                 hai = hai_first(hal);
223         } else {
224                 /* request is known */
225                 /* we check if record archive num is the same as the
226                  * known request, if not we will serve it in multiple
227                  * time because we do not know if the agent can serve
228                  * multiple backend a use case is a compound made of
229                  * multiple restore where the files are not archived
230                  * in the same backend */
231                 if (larr->arr_archive_id != request->hal->hal_archive_id)
232                         RETURN(0);
233
234                 if (request->hal_sz < request->hal_used_sz +
235                     cfs_size_round(larr->arr_hai.hai_len)) {
236                         /* Not enough room, need an extension */
237                         void *hal_buffer;
238                         int sz;
239
240                         sz = 2 * request->hal_sz;
241                         OBD_ALLOC(hal_buffer, sz);
242                         if (!hal_buffer)
243                                 RETURN(-ENOMEM);
244                         memcpy(hal_buffer, request->hal, request->hal_used_sz);
245                         OBD_FREE(request->hal, request->hal_sz);
246                         request->hal = hal_buffer;
247                         request->hal_sz = sz;
248                 }
249
250                 hai = hai_first(request->hal);
251                 for (i = 0; i < request->hal->hal_count; i++)
252                         hai = hai_next(hai);
253         }
254
255         memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
256         hai->hai_cookie = larr->arr_hai.hai_cookie;
257         hai->hai_gid = larr->arr_hai.hai_gid;
258
259         request->hal_used_sz += cfs_size_round(hai->hai_len);
260         request->hal->hal_count++;
261
262         if (hai->hai_action != HSMA_CANCEL)
263                 cdt_agent_record_hash_add(cdt, hai->hai_cookie,
264                                           llh->lgh_hdr->llh_cat_idx,
265                                           larr->arr_hdr.lrh_index);
266
267         RETURN(0);
268 }
269
270 static int mdt_cdt_started_cb(const struct lu_env *env,
271                               struct mdt_device *mdt,
272                               struct llog_handle *llh,
273                               struct llog_agent_req_rec *larr,
274                               struct hsm_scan_data *hsd)
275 {
276         struct coordinator *cdt = &mdt->mdt_coordinator;
277         struct hsm_progress_kernel pgs;
278         struct cdt_agent_req *car;
279         time64_t now = ktime_get_real_seconds();
280         time64_t last;
281         int rc;
282
283         if (!hsd->housekeeping)
284                 RETURN(0);
285
286         /* we search for a running request
287          * error may happen if coordinator crashes or stopped
288          * with running request
289          */
290         car = mdt_cdt_find_request(cdt, larr->arr_hai.hai_cookie);
291         if (car == NULL) {
292                 last = larr->arr_req_change;
293         } else {
294                 last = car->car_req_update;
295                 mdt_cdt_put_request(car);
296         }
297
298         /* test if request too long, if yes cancel it
299          * the same way the copy tool acknowledge a cancel request */
300         if (now <= last + cdt->cdt_active_req_timeout)
301                 RETURN(0);
302
303         dump_llog_agent_req_rec("request timed out, start cleaning", larr);
304         /* a too old cancel request just needs to be removed
305          * this can happen, if copy tool does not support
306          * cancel for other requests, we have to remove the
307          * running request and notify the copytool */
308         pgs.hpk_fid = larr->arr_hai.hai_fid;
309         pgs.hpk_cookie = larr->arr_hai.hai_cookie;
310         pgs.hpk_extent = larr->arr_hai.hai_extent;
311         pgs.hpk_flags = HP_FLAG_COMPLETED;
312         pgs.hpk_errval = ENOSYS;
313         pgs.hpk_data_version = 0;
314
315         /* update request state, but do not record in llog, to
316          * avoid deadlock on cdt_llog_lock */
317         rc = mdt_hsm_update_request_state(hsd->mti, &pgs, 0);
318         if (rc)
319                 CERROR("%s: cannot cleanup timed out request: "
320                        DFID" for cookie %#llx action=%s\n",
321                        mdt_obd_name(mdt),
322                        PFID(&pgs.hpk_fid), pgs.hpk_cookie,
323                        hsm_copytool_action2name(larr->arr_hai.hai_action));
324
325         if (rc == -ENOENT) {
326                 /* The request no longer exists, forget
327                  * about it, and do not send a cancel request
328                  * to the client, for which an error will be
329                  * sent back, leading to an endless cycle of
330                  * cancellation. */
331                 cdt_agent_record_hash_del(cdt, larr->arr_hai.hai_cookie);
332                 RETURN(LLOG_DEL_RECORD);
333         }
334
335         /* XXX A cancel request cannot be cancelled. */
336         if (larr->arr_hai.hai_action == HSMA_CANCEL)
337                 RETURN(0);
338
339         larr->arr_status = ARS_CANCELED;
340         larr->arr_req_change = now;
341         rc = llog_write(hsd->mti->mti_env, llh, &larr->arr_hdr,
342                         larr->arr_hdr.lrh_index);
343         if (rc < 0)
344                 CERROR("%s: cannot update agent log: rc = %d\n",
345                        mdt_obd_name(mdt), rc);
346
347         RETURN(0);
348 }
349
350 /**
351  *  llog_cat_process() callback, used to:
352  *  - find waiting request and start action
353  *  - purge canceled and done requests
354  * \param env [IN] environment
355  * \param llh [IN] llog handle
356  * \param hdr [IN] llog record
357  * \param data [IN/OUT] cb data = struct hsm_scan_data
358  * \retval 0 success
359  * \retval -ve failure
360  */
361 static int mdt_coordinator_cb(const struct lu_env *env,
362                               struct llog_handle *llh,
363                               struct llog_rec_hdr *hdr,
364                               void *data)
365 {
366         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
367         struct hsm_scan_data *hsd = data;
368         struct mdt_device *mdt = hsd->mti->mti_mdt;
369         struct coordinator *cdt = &mdt->mdt_coordinator;
370         ENTRY;
371
372         larr = (struct llog_agent_req_rec *)hdr;
373         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
374         switch (larr->arr_status) {
375         case ARS_WAITING:
376                 RETURN(mdt_cdt_waiting_cb(env, mdt, llh, larr, hsd));
377         case ARS_STARTED:
378                 RETURN(mdt_cdt_started_cb(env, mdt, llh, larr, hsd));
379         default:
380                 if (!hsd->housekeeping)
381                         RETURN(0);
382
383                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
384                     ktime_get_real_seconds()) {
385                         cdt_agent_record_hash_del(cdt,
386                                                   larr->arr_hai.hai_cookie);
387                         RETURN(LLOG_DEL_RECORD);
388                 }
389
390                 RETURN(0);
391         }
392 }
393
394 /**
395  * create /proc entries for coordinator
396  * \param mdt [IN]
397  * \retval 0 success
398  * \retval -ve failure
399  */
400 int hsm_cdt_procfs_init(struct mdt_device *mdt)
401 {
402         struct coordinator      *cdt = &mdt->mdt_coordinator;
403         int                      rc = 0;
404         ENTRY;
405
406         /* init /proc entries, failure is not critical */
407         cdt->cdt_proc_dir = lprocfs_register("hsm",
408                                              mdt2obd_dev(mdt)->obd_proc_entry,
409                                              lprocfs_mdt_hsm_vars, mdt);
410         if (IS_ERR(cdt->cdt_proc_dir)) {
411                 rc = PTR_ERR(cdt->cdt_proc_dir);
412                 CERROR("%s: Cannot create 'hsm' directory in mdt proc dir,"
413                        " rc=%d\n", mdt_obd_name(mdt), rc);
414                 cdt->cdt_proc_dir = NULL;
415                 RETURN(rc);
416         }
417
418         RETURN(0);
419 }
420
421 /**
422  * remove /proc entries for coordinator
423  * \param mdt [IN]
424  */
425 void hsm_cdt_procfs_fini(struct mdt_device *mdt)
426 {
427         struct coordinator *cdt = &mdt->mdt_coordinator;
428
429         if (cdt->cdt_proc_dir != NULL)
430                 lprocfs_remove(&cdt->cdt_proc_dir);
431 }
432
433 /**
434  * get vector of hsm cdt /proc vars
435  * \param none
436  * \retval var vector
437  */
438 struct lprocfs_vars *hsm_cdt_get_proc_vars(void)
439 {
440         return lprocfs_mdt_hsm_vars;
441 }
442
443 /* Release the ressource used by the coordinator. Called when the
444  * coordinator is stopping. */
445 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
446 {
447         struct coordinator              *cdt = &mdt->mdt_coordinator;
448         struct cdt_agent_req            *car, *tmp1;
449         struct hsm_agent                *ha, *tmp2;
450         struct cdt_restore_handle       *crh, *tmp3;
451         struct mdt_thread_info          *cdt_mti;
452
453         /* start cleaning */
454         down_write(&cdt->cdt_request_lock);
455         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
456                                  car_request_list) {
457                 cfs_hash_del(cdt->cdt_request_cookie_hash,
458                              &car->car_hai->hai_cookie,
459                              &car->car_cookie_hash);
460                 list_del(&car->car_request_list);
461                 mdt_cdt_put_request(car);
462         }
463         up_write(&cdt->cdt_request_lock);
464
465         down_write(&cdt->cdt_agent_lock);
466         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
467                 list_del(&ha->ha_list);
468                 OBD_FREE_PTR(ha);
469         }
470         up_write(&cdt->cdt_agent_lock);
471
472         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
473         mutex_lock(&cdt->cdt_restore_lock);
474         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_handle_list,
475                                  crh_list) {
476                 list_del(&crh->crh_list);
477                 /* give back layout lock */
478                 mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
479                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
480         }
481         mutex_unlock(&cdt->cdt_restore_lock);
482 }
483
484 /*
485  * Coordinator state transition table, indexed on enum cdt_states, taking
486  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
487  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
488  */
489 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
490         /* from -> to:    stopped init   running disable stopping */
491         /* stopped */   { true,   true,  false,  false,  false },
492         /* init */      { true,   false, true,   false,  false },
493         /* running */   { false,  false, true,   true,   true },
494         /* disable */   { false,  false, true,   true,   true },
495         /* stopping */  { true,   false, false,  false,  false }
496 };
497
498 /**
499  * Change coordinator thread state
500  * Some combinations are not valid, so catch them here.
501  *
502  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
503  * the transition was not possible.
504  */
505 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state,
506                          enum cdt_states *old_state)
507 {
508         int rc;
509         enum cdt_states state;
510
511         spin_lock(&cdt->cdt_state_lock);
512
513         state = cdt->cdt_state;
514
515         if (cdt_transition[state][new_state]) {
516                 cdt->cdt_state = new_state;
517                 spin_unlock(&cdt->cdt_state_lock);
518                 if (old_state)
519                         *old_state = state;
520                 rc = 0;
521         } else {
522                 spin_unlock(&cdt->cdt_state_lock);
523                 CDEBUG(D_HSM,
524                        "unexpected coordinator transition, from=%s, to=%s\n",
525                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
526                 rc = -EINVAL;
527         }
528
529         return rc;
530 }
531
532 /**
533  * coordinator thread
534  * \param data [IN] obd device
535  * \retval 0 success
536  * \retval -ve failure
537  */
538 static int mdt_coordinator(void *data)
539 {
540         struct hsm_thread_data  *thread_data = data;
541         struct mdt_thread_info  *mti = thread_data->cdt_mti;
542         struct mdt_device       *mdt = mti->mti_mdt;
543         struct coordinator      *cdt = &mdt->mdt_coordinator;
544         struct hsm_scan_data     hsd = { NULL };
545         time64_t                 last_housekeeping = 0;
546         int                      rc = 0;
547         int                      request_sz;
548         ENTRY;
549
550         /* set up hsd->request and max_requests */
551         hsd.max_requests = cdt->cdt_max_requests;
552         request_sz = hsd.max_requests * sizeof(*hsd.request);
553         hsd.request = thread_data->request;
554
555         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
556                mdt_obd_name(mdt), current_pid());
557
558         hsd.mti = mti;
559         obd_uuid2fsname(hsd.fs_name, mdt_obd_name(mdt), MTI_NAME_MAXLEN);
560
561         set_cdt_state(cdt, CDT_RUNNING, NULL);
562
563         /* Inform mdt_hsm_cdt_start(). */
564         wake_up_all(&cdt->cdt_waitq);
565
566         while (1) {
567                 int i;
568                 int update_idx = 0;
569                 int updates_sz;
570                 int updates_cnt;
571                 struct hsm_record_update *updates;
572
573                 /* Limit execution of the expensive requests traversal
574                  * to at most one second. This prevents repeatedly
575                  * locking/unlocking the catalog for each request
576                  * and preventing other HSM operations from happening
577                  */
578                 wait_event_interruptible_timeout(cdt->cdt_waitq,
579                                                  kthread_should_stop() ||
580                                                  cdt->cdt_wakeup_coordinator,
581                                                  cfs_time_seconds(1));
582
583                 cdt->cdt_wakeup_coordinator = false;
584                 CDEBUG(D_HSM, "coordinator resumes\n");
585
586                 if (kthread_should_stop()) {
587                         CDEBUG(D_HSM, "Coordinator stops\n");
588                         rc = 0;
589                         break;
590                 }
591
592                 /* if coordinator is suspended continue to wait */
593                 if (cdt->cdt_state == CDT_DISABLE) {
594                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
595                         continue;
596                 }
597
598                 /* If no event, and no housekeeping to do, continue to
599                  * wait. */
600                 if (last_housekeeping + cdt->cdt_loop_period <=
601                     ktime_get_real_seconds()) {
602                         last_housekeeping = ktime_get_real_seconds();
603                         hsd.housekeeping = true;
604                 } else if (cdt->cdt_event) {
605                         hsd.housekeeping = false;
606                 } else {
607                         continue;
608                 }
609
610                 cdt->cdt_event = false;
611
612                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
613
614                 if (hsd.max_requests != cdt->cdt_max_requests) {
615                         /* cdt_max_requests has changed,
616                          * we need to allocate a new buffer
617                          */
618                         struct hsm_scan_request *tmp = NULL;
619                         int max_requests = cdt->cdt_max_requests;
620                         OBD_ALLOC_LARGE(tmp, max_requests *
621                                         sizeof(struct hsm_scan_request));
622                         if (!tmp) {
623                                 CERROR("Failed to resize request buffer, "
624                                        "keeping it at %d\n",
625                                        hsd.max_requests);
626                                 cdt->cdt_max_requests = hsd.max_requests;
627                         } else {
628                                 OBD_FREE_LARGE(hsd.request, request_sz);
629                                 hsd.max_requests = max_requests;
630                                 request_sz = hsd.max_requests *
631                                         sizeof(struct hsm_scan_request);
632                                 hsd.request = tmp;
633                         }
634                 }
635
636                 hsd.request_cnt = 0;
637
638                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
639                                       &hsd, 0, 0, WRITE);
640                 if (rc < 0)
641                         goto clean_cb_alloc;
642
643                 CDEBUG(D_HSM, "found %d requests to send\n", hsd.request_cnt);
644
645                 if (list_empty(&cdt->cdt_agents)) {
646                         CDEBUG(D_HSM, "no agent available, "
647                                       "coordinator sleeps\n");
648                         goto clean_cb_alloc;
649                 }
650
651                 /* Compute how many HAI we have in all the requests */
652                 updates_cnt = 0;
653                 for (i = 0; i < hsd.request_cnt; i++) {
654                         const struct hsm_scan_request *request =
655                                 &hsd.request[i];
656
657                         updates_cnt += request->hal->hal_count;
658                 }
659
660                 /* Allocate a temporary array to store the cookies to
661                  * update, and their status. */
662                 updates_sz = updates_cnt * sizeof(*updates);
663                 OBD_ALLOC(updates, updates_sz);
664                 if (updates == NULL) {
665                         CERROR("%s: Cannot allocate memory (%d o) "
666                                "for %d updates\n",
667                                mdt_obd_name(mdt), updates_sz, updates_cnt);
668                         continue;
669                 }
670
671                 /* here hsd contains a list of requests to be started */
672                 for (i = 0; i < hsd.request_cnt; i++) {
673                         struct hsm_scan_request *request = &hsd.request[i];
674                         struct hsm_action_list  *hal = request->hal;
675                         struct hsm_action_item  *hai;
676                         int                      j;
677
678                         /* still room for work ? */
679                         if (atomic_read(&cdt->cdt_request_count) >=
680                             cdt->cdt_max_requests)
681                                 break;
682
683                         rc = mdt_hsm_agent_send(mti, hal, 0);
684                         /* if failure, we suppose it is temporary
685                          * if the copy tool failed to do the request
686                          * it has to use hsm_progress
687                          */
688
689                         /* set up cookie vector to set records status
690                          * after copy tools start or failed
691                          */
692                         hai = hai_first(hal);
693                         for (j = 0; j < hal->hal_count; j++) {
694                                 updates[update_idx].cookie = hai->hai_cookie;
695                                 updates[update_idx].status =
696                                         (rc ? ARS_WAITING : ARS_STARTED);
697                                 hai = hai_next(hai);
698                                 update_idx++;
699                         }
700                 }
701
702                 if (update_idx) {
703                         rc = mdt_agent_record_update(mti->mti_env, mdt,
704                                                      updates, update_idx);
705                         if (rc)
706                                 CERROR("%s: mdt_agent_record_update() failed, "
707                                        "rc=%d, cannot update records "
708                                        "for %d cookies\n",
709                                        mdt_obd_name(mdt), rc, update_idx);
710                 }
711
712                 OBD_FREE(updates, updates_sz);
713
714 clean_cb_alloc:
715                 /* free hal allocated by callback */
716                 for (i = 0; i < hsd.request_cnt; i++) {
717                         struct hsm_scan_request *request = &hsd.request[i];
718
719                         OBD_FREE(request->hal, request->hal_sz);
720                 }
721         }
722
723         if (hsd.request)
724                 OBD_FREE_LARGE(hsd.request, request_sz);
725
726         mdt_hsm_cdt_cleanup(mdt);
727
728         if (rc != 0)
729                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
730                        mdt_obd_name(mdt), current_pid(), rc);
731         else
732                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
733                               " no error\n",
734                        mdt_obd_name(mdt), current_pid());
735
736         RETURN(rc);
737 }
738
739 int cdt_restore_handle_add(struct mdt_thread_info *mti, struct coordinator *cdt,
740                            const struct lu_fid *fid,
741                            const struct hsm_extent *he)
742 {
743         struct cdt_restore_handle *crh;
744         struct mdt_object *obj;
745         int rc;
746         ENTRY;
747
748         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
749         if (crh == NULL)
750                 RETURN(-ENOMEM);
751
752         crh->crh_fid = *fid;
753         /* in V1 all file is restored
754          * crh->extent.start = he->offset;
755          * crh->extent.end = he->offset + he->length;
756          */
757         crh->crh_extent.start = 0;
758         crh->crh_extent.end = he->length;
759         /* get the layout lock */
760         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
761         obj = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
762                                    MDS_INODELOCK_LAYOUT);
763         if (IS_ERR(obj))
764                 GOTO(out_crh, rc = PTR_ERR(obj));
765
766         /* We do not keep a reference on the object during the restore
767          * which can be very long. */
768         mdt_object_put(mti->mti_env, obj);
769
770         mutex_lock(&cdt->cdt_restore_lock);
771         if (unlikely(cdt->cdt_state == CDT_STOPPED ||
772                      cdt->cdt_state == CDT_STOPPING)) {
773                 mutex_unlock(&cdt->cdt_restore_lock);
774                 GOTO(out_lh, rc = -EAGAIN);
775         }
776
777         list_add_tail(&crh->crh_list, &cdt->cdt_restore_handle_list);
778         mutex_unlock(&cdt->cdt_restore_lock);
779
780         RETURN(0);
781 out_lh:
782         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
783 out_crh:
784         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
785
786         return rc;
787 }
788
789 /**
790  * lookup a restore handle by FID
791  * caller needs to hold cdt_restore_lock
792  * \param cdt [IN] coordinator
793  * \param fid [IN] FID
794  * \retval cdt_restore_handle found
795  * \retval NULL not found
796  */
797 struct cdt_restore_handle *cdt_restore_handle_find(struct coordinator *cdt,
798                                                    const struct lu_fid *fid)
799 {
800         struct cdt_restore_handle *crh;
801         ENTRY;
802
803         list_for_each_entry(crh, &cdt->cdt_restore_handle_list, crh_list) {
804                 if (lu_fid_eq(&crh->crh_fid, fid))
805                         RETURN(crh);
806         }
807
808         RETURN(NULL);
809 }
810
811 void cdt_restore_handle_del(struct mdt_thread_info *mti,
812                             struct coordinator *cdt, const struct lu_fid *fid)
813 {
814         struct cdt_restore_handle *crh;
815
816         /* give back layout lock */
817         mutex_lock(&cdt->cdt_restore_lock);
818         crh = cdt_restore_handle_find(cdt, fid);
819         if (crh != NULL)
820                 list_del(&crh->crh_list);
821         mutex_unlock(&cdt->cdt_restore_lock);
822
823         if (crh == NULL)
824                 return;
825
826         /* XXX We pass a NULL object since the restore handle does not
827          * keep a reference on the object being restored. */
828         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
829         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
830 }
831
832 /**
833  * data passed to llog_cat_process() callback
834  * to scan requests and take actions
835  */
836 struct hsm_restore_data {
837         struct mdt_thread_info  *hrd_mti;
838 };
839
840 /**
841  *  llog_cat_process() callback, used to:
842  *  - find restore request and allocate the restore handle
843  * \param env [IN] environment
844  * \param llh [IN] llog handle
845  * \param hdr [IN] llog record
846  * \param data [IN/OUT] cb data = struct hsm_restore_data
847  * \retval 0 success
848  * \retval -ve failure
849  */
850 static int hsm_restore_cb(const struct lu_env *env,
851                           struct llog_handle *llh,
852                           struct llog_rec_hdr *hdr, void *data)
853 {
854         struct llog_agent_req_rec       *larr;
855         struct hsm_restore_data         *hrd;
856         struct hsm_action_item          *hai;
857         struct mdt_thread_info          *mti;
858         struct coordinator              *cdt;
859         int rc;
860         ENTRY;
861
862         hrd = data;
863         mti = hrd->hrd_mti;
864         cdt = &mti->mti_mdt->mdt_coordinator;
865
866         larr = (struct llog_agent_req_rec *)hdr;
867         hai = &larr->arr_hai;
868         if (hai->hai_cookie > cdt->cdt_last_cookie)
869                 /* update the cookie to avoid collision */
870                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
871
872         if (hai->hai_action != HSMA_RESTORE ||
873             agent_req_in_final_state(larr->arr_status))
874                 RETURN(0);
875
876         /* restore request not in a final state */
877
878         /* force replay of restore requests left in started state from previous
879          * CDT context, to be canceled later if finally found to be incompatible
880          * when being re-started */
881         if (larr->arr_status == ARS_STARTED) {
882                 larr->arr_status = ARS_WAITING;
883                 larr->arr_req_change = ktime_get_real_seconds();
884                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
885                 if (rc != 0)
886                         GOTO(out, rc);
887         }
888
889         rc = cdt_restore_handle_add(mti, cdt, &hai->hai_fid, &hai->hai_extent);
890 out:
891         RETURN(rc);
892 }
893
894 /**
895  * restore coordinator state at startup
896  * the goal is to take a layout lock for each registered restore request
897  * \param mti [IN] context
898  */
899 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
900 {
901         struct hsm_restore_data  hrd;
902         int                      rc;
903         ENTRY;
904
905         hrd.hrd_mti = mti;
906
907         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, hsm_restore_cb, &hrd,
908                               0, 0, WRITE);
909
910         RETURN(rc);
911 }
912
913 static int hsm_init_ucred(struct lu_ucred *uc)
914 {
915         ENTRY;
916
917         uc->uc_valid = UCRED_OLD;
918         uc->uc_o_uid = 0;
919         uc->uc_o_gid = 0;
920         uc->uc_o_fsuid = 0;
921         uc->uc_o_fsgid = 0;
922         uc->uc_uid = 0;
923         uc->uc_gid = 0;
924         uc->uc_fsuid = 0;
925         uc->uc_fsgid = 0;
926         uc->uc_suppgids[0] = -1;
927         uc->uc_suppgids[1] = -1;
928         uc->uc_cap = CFS_CAP_FS_MASK;
929         uc->uc_umask = 0777;
930         uc->uc_ginfo = NULL;
931         uc->uc_identity = NULL;
932
933         RETURN(0);
934 }
935
936 /**
937  * initialize coordinator struct
938  * \param mdt [IN] device
939  * \retval 0 success
940  * \retval -ve failure
941  */
942 int mdt_hsm_cdt_init(struct mdt_device *mdt)
943 {
944         struct coordinator      *cdt = &mdt->mdt_coordinator;
945         struct mdt_thread_info  *cdt_mti = NULL;
946         int                      rc;
947         ENTRY;
948
949         init_waitqueue_head(&cdt->cdt_waitq);
950         init_rwsem(&cdt->cdt_llog_lock);
951         init_rwsem(&cdt->cdt_agent_lock);
952         init_rwsem(&cdt->cdt_request_lock);
953         mutex_init(&cdt->cdt_restore_lock);
954         spin_lock_init(&cdt->cdt_state_lock);
955         set_cdt_state(cdt, CDT_STOPPED, NULL);
956
957         INIT_LIST_HEAD(&cdt->cdt_request_list);
958         INIT_LIST_HEAD(&cdt->cdt_agents);
959         INIT_LIST_HEAD(&cdt->cdt_restore_handle_list);
960
961         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
962                                                        CFS_HASH_BITS_MIN,
963                                                        CFS_HASH_BITS_MAX,
964                                                        CFS_HASH_BKT_BITS,
965                                                        0 /* extra bytes */,
966                                                        CFS_HASH_MIN_THETA,
967                                                        CFS_HASH_MAX_THETA,
968                                                 &cdt_request_cookie_hash_ops,
969                                                        CFS_HASH_DEFAULT);
970         if (cdt->cdt_request_cookie_hash == NULL)
971                 RETURN(-ENOMEM);
972
973         cdt->cdt_agent_record_hash = cfs_hash_create("AGENT_RECORD_HASH",
974                                                      CFS_HASH_BITS_MIN,
975                                                      CFS_HASH_BITS_MAX,
976                                                      CFS_HASH_BKT_BITS,
977                                                      0 /* extra bytes */,
978                                                      CFS_HASH_MIN_THETA,
979                                                      CFS_HASH_MAX_THETA,
980                                                      &cdt_agent_record_hash_ops,
981                                                      CFS_HASH_DEFAULT);
982         if (cdt->cdt_agent_record_hash == NULL)
983                 GOTO(out_request_cookie_hash, rc = -ENOMEM);
984
985         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
986         if (rc < 0)
987                 GOTO(out_agent_record_hash, rc);
988
989         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
990         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
991         if (rc < 0)
992                 GOTO(out_env, rc);
993
994         lu_context_enter(&cdt->cdt_session);
995         cdt->cdt_env.le_ses = &cdt->cdt_session;
996
997         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
998         LASSERT(cdt_mti != NULL);
999
1000         cdt_mti->mti_env = &cdt->cdt_env;
1001         cdt_mti->mti_mdt = mdt;
1002
1003         hsm_init_ucred(mdt_ucred(cdt_mti));
1004
1005         /* default values for /proc tunnables
1006          * can be override by MGS conf */
1007         cdt->cdt_default_archive_id = 1;
1008         cdt->cdt_grace_delay = 60;
1009         cdt->cdt_loop_period = 10;
1010         cdt->cdt_max_requests = 3;
1011         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1012         cdt->cdt_active_req_timeout = 3600;
1013
1014         /* Initialize cdt_compound_id here to allow its usage for
1015          * delayed requests from RAoLU policy */
1016         atomic_set(&cdt->cdt_compound_id, ktime_get_real_seconds());
1017
1018         /* by default do not remove archives on last unlink */
1019         cdt->cdt_remove_archive_on_last_unlink = false;
1020
1021         RETURN(0);
1022
1023 out_env:
1024         lu_env_fini(&cdt->cdt_env);
1025 out_agent_record_hash:
1026         cfs_hash_putref(cdt->cdt_agent_record_hash);
1027         cdt->cdt_agent_record_hash = NULL;
1028 out_request_cookie_hash:
1029         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1030         cdt->cdt_request_cookie_hash = NULL;
1031
1032         return rc;
1033 }
1034
1035 /**
1036  * free a coordinator thread
1037  * \param mdt [IN] device
1038  */
1039 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
1040 {
1041         struct coordinator *cdt = &mdt->mdt_coordinator;
1042         ENTRY;
1043
1044         lu_context_exit(cdt->cdt_env.le_ses);
1045         lu_context_fini(cdt->cdt_env.le_ses);
1046
1047         lu_env_fini(&cdt->cdt_env);
1048
1049         cfs_hash_putref(cdt->cdt_agent_record_hash);
1050         cdt->cdt_agent_record_hash = NULL;
1051
1052         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1053         cdt->cdt_request_cookie_hash = NULL;
1054
1055         RETURN(0);
1056 }
1057
1058 /**
1059  * start a coordinator thread
1060  * \param mdt [IN] device
1061  * \retval 0 success
1062  * \retval -ve failure
1063  */
1064 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
1065 {
1066         struct coordinator      *cdt = &mdt->mdt_coordinator;
1067         int                      rc;
1068         void                    *ptr;
1069         struct task_struct      *task;
1070         int                      request_sz;
1071         struct hsm_thread_data   thread_data;
1072         ENTRY;
1073
1074         /* functions defined but not yet used
1075          * this avoid compilation warning
1076          */
1077         ptr = dump_requests;
1078
1079         rc = set_cdt_state(cdt, CDT_INIT, NULL);
1080         if (rc) {
1081                 CERROR("%s: Coordinator already started or stopping\n",
1082                        mdt_obd_name(mdt));
1083                 RETURN(-EALREADY);
1084         }
1085
1086         CLASSERT(1 << (CDT_POLICY_SHIFT_COUNT - 1) == CDT_POLICY_LAST);
1087         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1088
1089         /* just need to be larger than previous one */
1090         /* cdt_last_cookie is protected by cdt_llog_lock */
1091         cdt->cdt_last_cookie = ktime_get_real_seconds();
1092         atomic_set(&cdt->cdt_request_count, 0);
1093         atomic_set(&cdt->cdt_archive_count, 0);
1094         atomic_set(&cdt->cdt_restore_count, 0);
1095         atomic_set(&cdt->cdt_remove_count, 0);
1096         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
1097         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
1098         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
1099
1100         /* to avoid deadlock when start is made through /proc
1101          * /proc entries are created by the coordinator thread */
1102
1103         /* set up list of started restore requests */
1104         thread_data.cdt_mti =
1105                 lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1106         rc = mdt_hsm_pending_restore(thread_data.cdt_mti);
1107         if (rc)
1108                 CERROR("%s: cannot take the layout locks needed"
1109                        " for registered restore: %d\n",
1110                        mdt_obd_name(mdt), rc);
1111
1112         if (mdt->mdt_bottom->dd_rdonly)
1113                 RETURN(0);
1114
1115         /* Allocate the initial hsd.request[] vector*/
1116         request_sz = cdt->cdt_max_requests * sizeof(struct hsm_scan_request);
1117         OBD_ALLOC_LARGE(thread_data.request, request_sz);
1118         if (!thread_data.request) {
1119                 set_cdt_state(cdt, CDT_STOPPED, NULL);
1120                 RETURN(-ENOMEM);
1121         }
1122
1123         task = kthread_run(mdt_coordinator, &thread_data, "hsm_cdtr");
1124         if (IS_ERR(task)) {
1125                 rc = PTR_ERR(task);
1126                 set_cdt_state(cdt, CDT_STOPPED, NULL);
1127                 OBD_FREE(thread_data.request, request_sz);
1128                 CERROR("%s: error starting coordinator thread: %d\n",
1129                        mdt_obd_name(mdt), rc);
1130         } else {
1131                 cdt->cdt_task = task;
1132                 wait_event(cdt->cdt_waitq,
1133                            cdt->cdt_state != CDT_INIT);
1134                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
1135                        mdt_obd_name(mdt));
1136                 rc = 0;
1137         }
1138
1139         RETURN(rc);
1140 }
1141
1142 /**
1143  * stop a coordinator thread
1144  * \param mdt [IN] device
1145  */
1146 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1147 {
1148         struct coordinator *cdt = &mdt->mdt_coordinator;
1149         int rc;
1150
1151         ENTRY;
1152         /* stop coordinator thread */
1153         rc = set_cdt_state(cdt, CDT_STOPPING, NULL);
1154         if (rc == 0) {
1155                 kthread_stop(cdt->cdt_task);
1156                 cdt->cdt_task = NULL;
1157                 set_cdt_state(cdt, CDT_STOPPED, NULL);
1158         }
1159
1160         RETURN(rc);
1161 }
1162
1163 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1164                               const struct lu_fid *fid,
1165                               u32 archive_id)
1166 {
1167         struct mdt_object *obj;
1168         struct md_hsm mh;
1169         int rc;
1170
1171         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1172         if (IS_ERR(obj))
1173                 GOTO(out, rc = PTR_ERR(obj));
1174
1175         if (mh.mh_flags & HS_EXISTS &&
1176             mh.mh_arch_id == archive_id)
1177                 GOTO(out_obj, rc = 0);
1178
1179         mh.mh_flags |= HS_EXISTS;
1180         mh.mh_arch_id = archive_id;
1181         rc = mdt_hsm_attr_set(mti, obj, &mh);
1182
1183 out_obj:
1184         mdt_object_put(mti->mti_env, obj);
1185 out:
1186         return rc;
1187 }
1188
1189 /**
1190  * register all requests from an hal in the memory list
1191  * \param mti [IN] context
1192  * \param hal [IN] request
1193  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1194  *  which is running the CT
1195  * \retval 0 success
1196  * \retval -ve failure
1197  */
1198 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1199                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1200 {
1201         struct mdt_device       *mdt = mti->mti_mdt;
1202         struct coordinator      *cdt = &mdt->mdt_coordinator;
1203         struct hsm_action_item  *hai;
1204         int                      rc = 0, i;
1205         ENTRY;
1206
1207         /* register request in memory list */
1208         hai = hai_first(hal);
1209         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1210                 struct cdt_agent_req *car;
1211
1212                 /* in case of a cancel request, we first mark the ondisk
1213                  * record of the request we want to stop as canceled
1214                  * this does not change the cancel record
1215                  * it will be done when updating the request status
1216                  */
1217                 if (hai->hai_action == HSMA_CANCEL) {
1218                         struct hsm_record_update update = {
1219                                 .cookie = hai->hai_cookie,
1220                                 .status = ARS_CANCELED,
1221                         };
1222
1223                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1224                                                      &update, 1);
1225                         if (rc) {
1226                                 CERROR("%s: mdt_agent_record_update() failed, "
1227                                        "rc=%d, cannot update status to %s "
1228                                        "for cookie %#llx\n",
1229                                        mdt_obd_name(mdt), rc,
1230                                        agent_req_status2name(ARS_CANCELED),
1231                                        hai->hai_cookie);
1232                                 GOTO(out, rc);
1233                         }
1234
1235                         /* find the running request to set it canceled */
1236                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1237                         if (car != NULL) {
1238                                 car->car_canceled = 1;
1239                                 /* uuid has to be changed to the one running the
1240                                 * request to cancel */
1241                                 *uuid = car->car_uuid;
1242                                 mdt_cdt_put_request(car);
1243                         }
1244                         /* no need to memorize cancel request
1245                          * this also avoid a deadlock when we receive
1246                          * a purge all requests command
1247                          */
1248                         continue;
1249                 }
1250
1251                 if (hai->hai_action == HSMA_ARCHIVE) {
1252                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1253                                                 hal->hal_archive_id);
1254                         if (rc == -ENOENT)
1255                                 continue;
1256                         else if (rc < 0)
1257                                 GOTO(out, rc);
1258                 }
1259
1260                 car = mdt_cdt_alloc_request(hal->hal_compound_id,
1261                                             hal->hal_archive_id, hal->hal_flags,
1262                                             uuid, hai);
1263                 if (IS_ERR(car))
1264                         GOTO(out, rc = PTR_ERR(car));
1265
1266                 rc = mdt_cdt_add_request(cdt, car);
1267                 if (rc != 0)
1268                         mdt_cdt_free_request(car);
1269         }
1270 out:
1271         RETURN(rc);
1272 }
1273
1274 /**
1275  * swap layouts between 2 fids
1276  * \param mti [IN] context
1277  * \param obj [IN]
1278  * \param dfid [IN]
1279  * \param mh_common [IN] MD HSM
1280  */
1281 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1282                             struct mdt_object *obj, const struct lu_fid *dfid,
1283                             struct md_hsm *mh_common)
1284 {
1285         struct mdt_object       *dobj;
1286         struct mdt_lock_handle  *dlh;
1287         int                      rc;
1288         ENTRY;
1289
1290         if (!mdt_object_exists(obj))
1291                 GOTO(out, rc = -ENOENT);
1292
1293         /* we already have layout lock on obj so take only
1294          * on dfid */
1295         dlh = &mti->mti_lh[MDT_LH_OLD];
1296         mdt_lock_reg_init(dlh, LCK_EX);
1297         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1298         if (IS_ERR(dobj))
1299                 GOTO(out, rc = PTR_ERR(dobj));
1300
1301         /* if copy tool closes the volatile before sending the final
1302          * progress through llapi_hsm_copy_end(), all the objects
1303          * are removed and mdd_swap_layout LBUG */
1304         if (!mdt_object_exists(dobj)) {
1305                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1306                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1307                 GOTO(out_dobj, rc = -ENOENT);
1308         }
1309         /* Since we only handle restores here, unconditionally use
1310          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1311          * be preserved in case of failure during swap_layout and not
1312          * leave a file in an intermediate but incoherent state.
1313          * But need to setup HSM xattr of data FID before, reuse
1314          * mti and mh presets for FID in hsm_cdt_request_completed(),
1315          * only need to clear RELEASED and DIRTY.
1316          */
1317         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1318         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1319         if (rc == 0)
1320                 rc = mo_swap_layouts(mti->mti_env,
1321                                      mdt_object_child(obj),
1322                                      mdt_object_child(dobj),
1323                                      SWAP_LAYOUTS_MDS_HSM);
1324
1325 out_dobj:
1326         mdt_object_unlock_put(mti, dobj, dlh, 1);
1327 out:
1328         RETURN(rc);
1329 }
1330
1331 /**
1332  * update status of a completed request
1333  * \param mti [IN] context
1334  * \param pgs [IN] progress of the copy tool
1335  * \param update_record [IN] update llog record
1336  * \retval 0 success
1337  * \retval -ve failure
1338  */
1339 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1340                                      struct hsm_progress_kernel *pgs,
1341                                      const struct cdt_agent_req *car,
1342                                      enum agent_req_status *status)
1343 {
1344         const struct lu_env     *env = mti->mti_env;
1345         struct mdt_device       *mdt = mti->mti_mdt;
1346         struct coordinator      *cdt = &mdt->mdt_coordinator;
1347         struct mdt_object       *obj = NULL;
1348         int                      cl_flags = 0, rc = 0;
1349         struct md_hsm            mh;
1350         bool                     is_mh_changed;
1351         bool                     need_changelog = true;
1352         ENTRY;
1353
1354         /* default is to retry */
1355         *status = ARS_WAITING;
1356
1357         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1358          * if error/removed continue anyway to get correct reporting done */
1359         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1360         /* we will update MD HSM only if needed */
1361         is_mh_changed = false;
1362
1363         /* no need to change mh->mh_arch_id
1364          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1365          */
1366         if (pgs->hpk_errval != 0) {
1367                 switch (pgs->hpk_errval) {
1368                 case ENOSYS:
1369                         /* the copy tool does not support cancel
1370                          * so the cancel request is failed
1371                          * As we cannot distinguish a cancel progress
1372                          * from another action progress (they have the
1373                          * same cookie), we suppose here the CT returns
1374                          * ENOSYS only if does not support cancel
1375                          */
1376                         /* this can also happen when cdt calls it to
1377                          * for a timed out request */
1378                         *status = ARS_FAILED;
1379                         /* to have a cancel event in changelog */
1380                         pgs->hpk_errval = ECANCELED;
1381                         break;
1382                 case ECANCELED:
1383                         /* the request record has already been set to
1384                          * ARS_CANCELED, this set the cancel request
1385                          * to ARS_SUCCEED */
1386                         *status = ARS_SUCCEED;
1387                         break;
1388                 default:
1389                         /* retry only if current policy or requested, and
1390                          * object is not on error/removed */
1391                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1392                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1393                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1394                         break;
1395                 }
1396
1397                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1398                         CERROR("%s: Request %#llx on "DFID
1399                                " failed, error code %d too large\n",
1400                                mdt_obd_name(mdt),
1401                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1402                                pgs->hpk_errval);
1403                         hsm_set_cl_error(&cl_flags,
1404                                          CLF_HSM_ERROVERFLOW);
1405                         rc = -EINVAL;
1406                 } else {
1407                         hsm_set_cl_error(&cl_flags, pgs->hpk_errval);
1408                 }
1409
1410                 switch (car->car_hai->hai_action) {
1411                 case HSMA_ARCHIVE:
1412                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1413                         break;
1414                 case HSMA_RESTORE:
1415                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1416                         break;
1417                 case HSMA_REMOVE:
1418                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1419                         break;
1420                 case HSMA_CANCEL:
1421                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1422                         CERROR("%s: Failed request %#llx on "DFID
1423                                " cannot be a CANCEL\n",
1424                                mdt_obd_name(mdt),
1425                                pgs->hpk_cookie,
1426                                PFID(&pgs->hpk_fid));
1427                         break;
1428                 default:
1429                         CERROR("%s: Failed request %#llx on "DFID
1430                                " %d is an unknown action\n",
1431                                mdt_obd_name(mdt),
1432                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1433                                car->car_hai->hai_action);
1434                         rc = -EINVAL;
1435                         break;
1436                 }
1437         } else {
1438                 *status = ARS_SUCCEED;
1439                 switch (car->car_hai->hai_action) {
1440                 case HSMA_ARCHIVE:
1441                         hsm_set_cl_event(&cl_flags, HE_ARCHIVE);
1442                         /* set ARCHIVE keep EXIST and clear LOST and
1443                          * DIRTY */
1444                         mh.mh_arch_ver = pgs->hpk_data_version;
1445                         mh.mh_flags |= HS_ARCHIVED;
1446                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1447                         is_mh_changed = true;
1448                         break;
1449                 case HSMA_RESTORE:
1450                         hsm_set_cl_event(&cl_flags, HE_RESTORE);
1451
1452                         /* do not clear RELEASED and DIRTY here
1453                          * this will occur in hsm_swap_layouts()
1454                          */
1455
1456                         /* Restoring has changed the file version on
1457                          * disk. */
1458                         mh.mh_arch_ver = pgs->hpk_data_version;
1459                         is_mh_changed = true;
1460                         break;
1461                 case HSMA_REMOVE:
1462                         hsm_set_cl_event(&cl_flags, HE_REMOVE);
1463                         /* clear ARCHIVED EXISTS and LOST */
1464                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1465                         is_mh_changed = true;
1466                         break;
1467                 case HSMA_CANCEL:
1468                         hsm_set_cl_event(&cl_flags, HE_CANCEL);
1469                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1470                                mdt_obd_name(mdt),
1471                                pgs->hpk_cookie,
1472                                PFID(&pgs->hpk_fid));
1473                         break;
1474                 default:
1475                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1476                                mdt_obd_name(mdt),
1477                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1478                                car->car_hai->hai_action);
1479                         rc = -EINVAL;
1480                         break;
1481                 }
1482         }
1483
1484         /* rc != 0 means error when analysing action, it may come from
1485          * a crasy CT no need to manage DIRTY
1486          * and if mdt_hsm_get_md_hsm() has returned an error, mh has not been
1487          * filled
1488          */
1489         if (rc == 0 && !IS_ERR(obj))
1490                 hsm_set_cl_flags(&cl_flags,
1491                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1492
1493         /* unlock is done later, after layout lock management */
1494         if (is_mh_changed && !IS_ERR(obj))
1495                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1496
1497         /* we give back layout lock only if restore was successful or
1498          * if no retry will be attempted and if object is still alive,
1499          * in other cases we just unlock the object */
1500         if (car->car_hai->hai_action == HSMA_RESTORE) {
1501                 /* restore in data FID done, we swap the layouts
1502                  * only if restore is successful */
1503                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1504                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1505                                               &mh);
1506                         if (rc) {
1507                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1508                                         *status = ARS_FAILED;
1509                                 pgs->hpk_errval = -rc;
1510                         }
1511                 }
1512                 /* we have to retry, so keep layout lock */
1513                 if (*status == ARS_WAITING)
1514                         GOTO(out, rc);
1515
1516                 /* restore special case, need to create ChangeLog record
1517                  * before to give back layout lock to avoid concurrent
1518                  * file updater to post out of order ChangeLog */
1519                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1520                              &car->car_hai->hai_fid);
1521                 need_changelog = false;
1522
1523                 cdt_restore_handle_del(mti, cdt, &car->car_hai->hai_fid);
1524         }
1525
1526         GOTO(out, rc);
1527
1528 out:
1529         /* always add a ChangeLog record */
1530         if (need_changelog)
1531                 mo_changelog(env, CL_HSM, cl_flags, mdt->mdt_child,
1532                              &car->car_hai->hai_fid);
1533
1534         if (!IS_ERR(obj))
1535                 mdt_object_put(mti->mti_env, obj);
1536
1537         RETURN(rc);
1538 }
1539
1540 /**
1541  * update status of a request
1542  * \param mti [IN] context
1543  * \param pgs [IN] progress of the copy tool
1544  * \param update_record [IN] update llog record
1545  * \retval 0 success
1546  * \retval -ve failure
1547  */
1548 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1549                                  struct hsm_progress_kernel *pgs,
1550                                  const int update_record)
1551 {
1552         struct mdt_device       *mdt = mti->mti_mdt;
1553         struct coordinator      *cdt = &mdt->mdt_coordinator;
1554         struct cdt_agent_req    *car;
1555         int                      rc = 0;
1556         ENTRY;
1557
1558         /* no coordinator started, so we cannot serve requests */
1559         if (cdt->cdt_state == CDT_STOPPED)
1560                 RETURN(-EAGAIN);
1561
1562         /* first do sanity checks */
1563         car = mdt_cdt_update_request(cdt, pgs);
1564         if (IS_ERR(car)) {
1565                 CERROR("%s: Cannot find running request for cookie %#llx"
1566                        " on fid="DFID"\n",
1567                        mdt_obd_name(mdt),
1568                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1569
1570                 RETURN(PTR_ERR(car));
1571         }
1572
1573         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1574                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1575                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1576                       hsm_copytool_action2name(car->car_hai->hai_action),
1577                       pgs->hpk_flags, pgs->hpk_errval,
1578                       PFID(&car->car_hai->hai_fid),
1579                       PFID(&car->car_hai->hai_dfid));
1580
1581         /* progress is done on FID or data FID depending of the action and
1582          * of the copy progress */
1583         /* for restore progress is used to send back the data FID to cdt */
1584         if (car->car_hai->hai_action == HSMA_RESTORE &&
1585             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1586                 car->car_hai->hai_dfid = pgs->hpk_fid;
1587
1588         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1589              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1590             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1591              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1592                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1593                        " does not match request FID "DFID" nor data FID "
1594                        DFID"\n",
1595                        mdt_obd_name(mdt),
1596                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1597                        PFID(&car->car_hai->hai_fid),
1598                        PFID(&car->car_hai->hai_dfid));
1599                 GOTO(out, rc = -EINVAL);
1600         }
1601
1602         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1603                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1604                        " is not coherent (err=%d and not completed"
1605                        " (flags=%d))\n",
1606                        mdt_obd_name(mdt),
1607                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1608                        hsm_copytool_action2name(car->car_hai->hai_action),
1609                        pgs->hpk_errval, pgs->hpk_flags);
1610                 GOTO(out, rc = -EINVAL);
1611         }
1612
1613         /* now progress is valid */
1614
1615         /* we use a root like ucred */
1616         hsm_init_ucred(mdt_ucred(mti));
1617
1618         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1619                 enum agent_req_status    status;
1620
1621                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1622
1623                 CDEBUG(D_HSM, "%s record: fid="DFID" cookie=%#llx action=%s "
1624                               "status=%s\n",
1625                        update_record ? "Updating" : "Not updating",
1626                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1627                        hsm_copytool_action2name(car->car_hai->hai_action),
1628                        agent_req_status2name(status));
1629
1630                 /* update record first (LU-9075) */
1631                 if (update_record) {
1632                         int rc1;
1633                         struct hsm_record_update update = {
1634                                 .cookie = pgs->hpk_cookie,
1635                                 .status = status,
1636                         };
1637
1638                         rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1639                                                       &update, 1);
1640                         if (rc1)
1641                                 CERROR("%s: mdt_agent_record_update() failed,"
1642                                        " rc=%d, cannot update status to %s"
1643                                        " for cookie %#llx\n",
1644                                        mdt_obd_name(mdt), rc1,
1645                                        agent_req_status2name(status),
1646                                        pgs->hpk_cookie);
1647                         rc = (rc != 0 ? rc : rc1);
1648                 }
1649
1650                 /* then remove request from memory list (LU-9075) */
1651                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1652
1653                 /* ct has completed a request, so a slot is available,
1654                  * signal the coordinator to find new work */
1655                 mdt_hsm_cdt_event(cdt);
1656         } else {
1657                 /* if copytool send a progress on a canceled request
1658                  * we inform copytool it should stop
1659                  */
1660                 if (car->car_canceled == 1)
1661                         rc = -ECANCELED;
1662         }
1663         GOTO(out, rc);
1664
1665 out:
1666         /* remove ref got from mdt_cdt_update_request() */
1667         mdt_cdt_put_request(car);
1668
1669         return rc;
1670 }
1671
1672
1673 /**
1674  * data passed to llog_cat_process() callback
1675  * to cancel requests
1676  */
1677 struct hsm_cancel_all_data {
1678         struct mdt_device       *mdt;
1679 };
1680
1681 /**
1682  *  llog_cat_process() callback, used to:
1683  *  - purge all requests
1684  * \param env [IN] environment
1685  * \param llh [IN] llog handle
1686  * \param hdr [IN] llog record
1687  * \param data [IN] cb data = struct hsm_cancel_all_data
1688  * \retval 0 success
1689  * \retval -ve failure
1690  */
1691 static int mdt_cancel_all_cb(const struct lu_env *env,
1692                              struct llog_handle *llh,
1693                              struct llog_rec_hdr *hdr, void *data)
1694 {
1695         struct llog_agent_req_rec       *larr;
1696         struct hsm_cancel_all_data      *hcad;
1697         int                              rc = 0;
1698         ENTRY;
1699
1700         larr = (struct llog_agent_req_rec *)hdr;
1701         hcad = data;
1702         if (larr->arr_status == ARS_WAITING ||
1703             larr->arr_status == ARS_STARTED) {
1704                 larr->arr_status = ARS_CANCELED;
1705                 larr->arr_req_change = ktime_get_real_seconds();
1706                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1707         }
1708
1709         RETURN(rc);
1710 }
1711
1712 /**
1713  * cancel all actions
1714  * \param obd [IN] MDT device
1715  */
1716 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1717 {
1718         struct lu_env                    env;
1719         struct lu_context                session;
1720         struct mdt_thread_info          *mti;
1721         struct coordinator              *cdt = &mdt->mdt_coordinator;
1722         struct cdt_agent_req            *car;
1723         struct hsm_action_list          *hal = NULL;
1724         struct hsm_action_item          *hai;
1725         struct hsm_cancel_all_data       hcad;
1726         int                              hal_sz = 0, hal_len, rc;
1727         enum cdt_states                  old_state;
1728         ENTRY;
1729
1730         rc = lu_env_init(&env, LCT_MD_THREAD);
1731         if (rc < 0)
1732                 RETURN(rc);
1733
1734         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1735         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1736         if (rc < 0)
1737                 GOTO(out_env, rc);
1738
1739         lu_context_enter(&session);
1740         env.le_ses = &session;
1741
1742         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1743         LASSERT(mti != NULL);
1744
1745         mti->mti_env = &env;
1746         mti->mti_mdt = mdt;
1747
1748         hsm_init_ucred(mdt_ucred(mti));
1749
1750         /* disable coordinator */
1751         rc = set_cdt_state(cdt, CDT_DISABLE, &old_state);
1752         if (rc)
1753                 RETURN(rc);
1754
1755         /* send cancel to all running requests */
1756         down_read(&cdt->cdt_request_lock);
1757         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1758                 mdt_cdt_get_request(car);
1759                 /* request is not yet removed from list, it will be done
1760                  * when copytool will return progress
1761                  */
1762
1763                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1764                         mdt_cdt_put_request(car);
1765                         continue;
1766                 }
1767
1768                 /* needed size */
1769                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1770                           cfs_size_round(car->car_hai->hai_len);
1771
1772                 if (hal_len > hal_sz && hal_sz > 0) {
1773                         /* not enough room, free old buffer */
1774                         OBD_FREE(hal, hal_sz);
1775                         hal = NULL;
1776                 }
1777
1778                 /* empty buffer, allocate one */
1779                 if (hal == NULL) {
1780                         hal_sz = hal_len;
1781                         OBD_ALLOC(hal, hal_sz);
1782                         if (hal == NULL) {
1783                                 mdt_cdt_put_request(car);
1784                                 up_read(&cdt->cdt_request_lock);
1785                                 GOTO(out_cdt_state, rc = -ENOMEM);
1786                         }
1787                 }
1788
1789                 hal->hal_version = HAL_VERSION;
1790                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1791                                 MTI_NAME_MAXLEN);
1792                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1793                 hal->hal_compound_id = car->car_compound_id;
1794                 hal->hal_archive_id = car->car_archive_id;
1795                 hal->hal_flags = car->car_flags;
1796                 hal->hal_count = 0;
1797
1798                 hai = hai_first(hal);
1799                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1800                 hai->hai_action = HSMA_CANCEL;
1801                 hal->hal_count = 1;
1802
1803                 /* it is possible to safely call mdt_hsm_agent_send()
1804                  * (ie without a deadlock on cdt_request_lock), because the
1805                  * write lock is taken only if we are not in purge mode
1806                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1807                  *   nor mdt_cdt_remove_request())
1808                  */
1809                 /* no conflict with cdt thread because cdt is disable and we
1810                  * have the request lock */
1811                 mdt_hsm_agent_send(mti, hal, 1);
1812
1813                 mdt_cdt_put_request(car);
1814         }
1815         up_read(&cdt->cdt_request_lock);
1816
1817         if (hal != NULL)
1818                 OBD_FREE(hal, hal_sz);
1819
1820         /* cancel all on-disk records */
1821         hcad.mdt = mdt;
1822
1823         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, mdt_cancel_all_cb,
1824                               &hcad, 0, 0, WRITE);
1825 out_cdt_state:
1826         /* Enable coordinator, unless the coordinator was stopping. */
1827         set_cdt_state(cdt, old_state, NULL);
1828         lu_context_exit(&session);
1829         lu_context_fini(&session);
1830 out_env:
1831         lu_env_fini(&env);
1832
1833         RETURN(rc);
1834 }
1835
1836 /**
1837  * check if a request is compatible with file status
1838  * \param hai [IN] request description
1839  * \param archive_id [IN] request archive id
1840  * \param rq_flags [IN] request flags
1841  * \param hsm [IN] file HSM metadata
1842  * \retval boolean
1843  */
1844 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1845                               u32 archive_id, u64 rq_flags,
1846                               const struct md_hsm *hsm)
1847 {
1848         int      is_compat = false;
1849         int      hsm_flags;
1850         ENTRY;
1851
1852         hsm_flags = hsm->mh_flags;
1853         switch (hai->hai_action) {
1854         case HSMA_ARCHIVE:
1855                 if (!(hsm_flags & HS_NOARCHIVE) &&
1856                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1857                         is_compat = true;
1858
1859                 if (hsm_flags & HS_EXISTS &&
1860                     archive_id != 0 &&
1861                     archive_id != hsm->mh_arch_id)
1862                         is_compat = false;
1863
1864                 break;
1865         case HSMA_RESTORE:
1866                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1867                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1868                         is_compat = true;
1869                 break;
1870         case HSMA_REMOVE:
1871                 if (!(hsm_flags & HS_RELEASED) &&
1872                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1873                         is_compat = true;
1874                 break;
1875         case HSMA_CANCEL:
1876                 is_compat = true;
1877                 break;
1878         }
1879         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1880                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1881                       PFID(&hai->hai_fid),
1882                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1883                       hai->hai_extent.offset, hai->hai_extent.length,
1884                       hsm->mh_flags,
1885                       (is_compat ? "compatible" : "uncompatible"));
1886
1887         RETURN(is_compat);
1888 }
1889
1890 /*
1891  * /proc interface used to get/set HSM behaviour (cdt->cdt_policy)
1892  */
1893 static const struct {
1894         __u64            bit;
1895         char            *name;
1896         char            *nickname;
1897 } hsm_policy_names[] = {
1898         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1899         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1900         { 0 },
1901 };
1902
1903 /**
1904  * convert a policy name to a bit
1905  * \param name [IN] policy name
1906  * \retval 0 unknown
1907  * \retval   policy bit
1908  */
1909 static __u64 hsm_policy_str2bit(const char *name)
1910 {
1911         int      i;
1912
1913         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1914                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1915                     strcmp(hsm_policy_names[i].name, name) == 0)
1916                         return hsm_policy_names[i].bit;
1917         return 0;
1918 }
1919
1920 /**
1921  * convert a policy bit field to a string
1922  * \param mask [IN] policy bit field
1923  * \param hexa [IN] print mask before bit names
1924  * \param buffer [OUT] string
1925  * \param count [IN] size of buffer
1926  */
1927 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1928                                 const bool hexa)
1929 {
1930         int      i, j;
1931         __u64    bit;
1932         ENTRY;
1933
1934         if (hexa)
1935                 seq_printf(m, "(%#llx) ", mask);
1936
1937         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1938                 bit = (1ULL << i);
1939
1940                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1941                         if (hsm_policy_names[j].bit == bit)
1942                                 break;
1943                 }
1944                 if (bit & mask)
1945                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1946                 else
1947                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1948         }
1949         /* remove last ' ' */
1950         m->count--;
1951         seq_putc(m, '\n');
1952 }
1953
1954 /* methods to read/write HSM policy flags */
1955 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
1956 {
1957         struct mdt_device       *mdt = m->private;
1958         struct coordinator      *cdt = &mdt->mdt_coordinator;
1959         ENTRY;
1960
1961         hsm_policy_bit2str(m, cdt->cdt_policy, false);
1962         RETURN(0);
1963 }
1964
1965 static ssize_t
1966 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
1967                          size_t count, loff_t *off)
1968 {
1969         struct seq_file         *m = file->private_data;
1970         struct mdt_device       *mdt = m->private;
1971         struct coordinator      *cdt = &mdt->mdt_coordinator;
1972         char                    *start, *token, sign;
1973         char                    *buf;
1974         __u64                    policy;
1975         __u64                    add_mask, remove_mask, set_mask;
1976         int                      rc;
1977         ENTRY;
1978
1979         if (count + 1 > PAGE_SIZE)
1980                 RETURN(-EINVAL);
1981
1982         OBD_ALLOC(buf, count + 1);
1983         if (buf == NULL)
1984                 RETURN(-ENOMEM);
1985
1986         if (copy_from_user(buf, buffer, count))
1987                 GOTO(out, rc = -EFAULT);
1988
1989         buf[count] = '\0';
1990
1991         start = buf;
1992         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
1993                start);
1994
1995         add_mask = remove_mask = set_mask = 0;
1996         do {
1997                 token = strsep(&start, "\n ");
1998                 sign = *token;
1999
2000                 if (sign == '\0')
2001                         continue;
2002
2003                 if (sign == '-' || sign == '+')
2004                         token++;
2005
2006                 policy = hsm_policy_str2bit(token);
2007                 if (policy == 0) {
2008                         CWARN("%s: '%s' is unknown, "
2009                               "supported policies are:\n", mdt_obd_name(mdt),
2010                               token);
2011                         hsm_policy_bit2str(m, 0, false);
2012                         GOTO(out, rc = -EINVAL);
2013                 }
2014                 switch (sign) {
2015                 case '-':
2016                         remove_mask |= policy;
2017                         break;
2018                 case '+':
2019                         add_mask |= policy;
2020                         break;
2021                 default:
2022                         set_mask |= policy;
2023                         break;
2024                 }
2025
2026         } while (start != NULL);
2027
2028         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
2029                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
2030
2031         /* if no sign in all string, it is a clear and set
2032          * if some sign found, all unsigned are converted
2033          * to add
2034          * P1 P2 = set to P1 and P2
2035          * P1 -P2 = add P1 clear P2 same as +P1 -P2
2036          */
2037         if (remove_mask == 0 && add_mask == 0) {
2038                 cdt->cdt_policy = set_mask;
2039         } else {
2040                 cdt->cdt_policy |= set_mask | add_mask;
2041                 cdt->cdt_policy &= ~remove_mask;
2042         }
2043
2044         GOTO(out, rc = count);
2045
2046 out:
2047         OBD_FREE(buf, count + 1);
2048         RETURN(rc);
2049 }
2050 LPROC_SEQ_FOPS(mdt_hsm_policy);
2051
2052 #define GENERATE_PROC_METHOD(VAR)                                       \
2053 static int mdt_hsm_##VAR##_seq_show(struct seq_file *m, void *data)     \
2054 {                                                                       \
2055         struct mdt_device       *mdt = m->private;                      \
2056         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
2057         ENTRY;                                                          \
2058                                                                         \
2059         seq_printf(m, "%llu\n", (__u64)cdt->VAR);                       \
2060         RETURN(0);                                                      \
2061 }                                                                       \
2062 static ssize_t                                                          \
2063 mdt_hsm_##VAR##_seq_write(struct file *file, const char __user *buffer, \
2064                           size_t count, loff_t *off)                    \
2065                                                                         \
2066 {                                                                       \
2067         struct seq_file         *m = file->private_data;                \
2068         struct mdt_device       *mdt = m->private;                      \
2069         struct coordinator      *cdt = &mdt->mdt_coordinator;           \
2070         __s64                    val;                                   \
2071         int                      rc;                                    \
2072         ENTRY;                                                          \
2073                                                                         \
2074         rc = lprocfs_str_to_s64(buffer, count, &val);                   \
2075         if (rc)                                                         \
2076                 RETURN(rc);                                             \
2077         if (val > 0 && val < INT_MAX) {                                 \
2078                 cdt->VAR = val;                                         \
2079                 RETURN(count);                                          \
2080         }                                                               \
2081         RETURN(-EINVAL);                                                \
2082 }                                                                       \
2083
2084 GENERATE_PROC_METHOD(cdt_loop_period)
2085 GENERATE_PROC_METHOD(cdt_grace_delay)
2086 GENERATE_PROC_METHOD(cdt_active_req_timeout)
2087 GENERATE_PROC_METHOD(cdt_max_requests)
2088 GENERATE_PROC_METHOD(cdt_default_archive_id)
2089
2090 /*
2091  * procfs write method for MDT/hsm_control
2092  * proc entry is in mdt directory so data is mdt obd_device pointer
2093  */
2094 #define CDT_ENABLE_CMD   "enabled"
2095 #define CDT_STOP_CMD     "shutdown"
2096 #define CDT_DISABLE_CMD  "disabled"
2097 #define CDT_PURGE_CMD    "purge"
2098 #define CDT_HELP_CMD     "help"
2099 #define CDT_MAX_CMD_LEN  10
2100
2101 ssize_t
2102 mdt_hsm_cdt_control_seq_write(struct file *file, const char __user *buffer,
2103                               size_t count, loff_t *off)
2104 {
2105         struct seq_file         *m = file->private_data;
2106         struct obd_device       *obd = m->private;
2107         struct mdt_device       *mdt = mdt_dev(obd->obd_lu_dev);
2108         struct coordinator      *cdt = &(mdt->mdt_coordinator);
2109         int                      rc, usage = 0;
2110         char                     kernbuf[CDT_MAX_CMD_LEN];
2111         ENTRY;
2112
2113         if (count == 0 || count >= sizeof(kernbuf))
2114                 RETURN(-EINVAL);
2115
2116         if (copy_from_user(kernbuf, buffer, count))
2117                 RETURN(-EFAULT);
2118         kernbuf[count] = 0;
2119
2120         if (kernbuf[count - 1] == '\n')
2121                 kernbuf[count - 1] = 0;
2122
2123         rc = 0;
2124         if (strcmp(kernbuf, CDT_ENABLE_CMD) == 0) {
2125                 if (cdt->cdt_state == CDT_DISABLE) {
2126                         rc = set_cdt_state(cdt, CDT_RUNNING, NULL);
2127                         mdt_hsm_cdt_event(cdt);
2128                         wake_up(&cdt->cdt_waitq);
2129                 } else {
2130                         rc = mdt_hsm_cdt_start(mdt);
2131                 }
2132         } else if (strcmp(kernbuf, CDT_STOP_CMD) == 0) {
2133                 if ((cdt->cdt_state == CDT_STOPPING) ||
2134                     (cdt->cdt_state == CDT_STOPPED)) {
2135                         CERROR("%s: Coordinator already stopped\n",
2136                                mdt_obd_name(mdt));
2137                         rc = -EALREADY;
2138                 } else {
2139                         rc = mdt_hsm_cdt_stop(mdt);
2140                 }
2141         } else if (strcmp(kernbuf, CDT_DISABLE_CMD) == 0) {
2142                 if ((cdt->cdt_state == CDT_STOPPING) ||
2143                     (cdt->cdt_state == CDT_STOPPED)) {
2144                         CERROR("%s: Coordinator is stopped\n",
2145                                mdt_obd_name(mdt));
2146                         rc = -EINVAL;
2147                 } else {
2148                         rc = set_cdt_state(cdt, CDT_DISABLE, NULL);
2149                 }
2150         } else if (strcmp(kernbuf, CDT_PURGE_CMD) == 0) {
2151                 rc = hsm_cancel_all_actions(mdt);
2152         } else if (strcmp(kernbuf, CDT_HELP_CMD) == 0) {
2153                 usage = 1;
2154         } else {
2155                 usage = 1;
2156                 rc = -EINVAL;
2157         }
2158
2159         if (usage == 1)
2160                 CERROR("%s: Valid coordinator control commands are: "
2161                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2162                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2163                        CDT_PURGE_CMD, CDT_HELP_CMD);
2164
2165         if (rc)
2166                 RETURN(rc);
2167
2168         RETURN(count);
2169 }
2170
2171 int mdt_hsm_cdt_control_seq_show(struct seq_file *m, void *data)
2172 {
2173         struct obd_device       *obd = m->private;
2174         struct coordinator      *cdt;
2175         ENTRY;
2176
2177         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2178
2179         seq_printf(m, "%s\n", cdt_mdt_state2str(cdt->cdt_state));
2180
2181         RETURN(0);
2182 }
2183
2184 static int
2185 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2186 {
2187         bool first = true;
2188         int i;
2189         ENTRY;
2190
2191         for (i = 0; i < 8 * sizeof(mask); i++) {
2192                 if (mask & (1UL << i)) {
2193                         seq_printf(m, "%s%s", first ? "" : " ",
2194                                    hsm_copytool_action2name(i));
2195                         first = false;
2196                 }
2197         }
2198         seq_putc(m, '\n');
2199
2200         RETURN(0);
2201 }
2202
2203 static int
2204 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2205 {
2206         struct mdt_device *mdt = m->private;
2207         struct coordinator *cdt = &mdt->mdt_coordinator;
2208
2209         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2210 }
2211
2212 static int
2213 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2214 {
2215         struct mdt_device *mdt = m->private;
2216         struct coordinator *cdt = &mdt->mdt_coordinator;
2217
2218         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2219 }
2220
2221 static int
2222 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2223 {
2224         struct mdt_device *mdt = m->private;
2225         struct coordinator *cdt = &mdt->mdt_coordinator;
2226
2227         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2228 }
2229
2230 static inline enum hsm_copytool_action
2231 hsm_copytool_name2action(const char *name)
2232 {
2233         if (strcasecmp(name, "NOOP") == 0)
2234                 return HSMA_NONE;
2235         else if (strcasecmp(name, "ARCHIVE") == 0)
2236                 return HSMA_ARCHIVE;
2237         else if (strcasecmp(name, "RESTORE") == 0)
2238                 return HSMA_RESTORE;
2239         else if (strcasecmp(name, "REMOVE") == 0)
2240                 return HSMA_REMOVE;
2241         else if (strcasecmp(name, "CANCEL") == 0)
2242                 return HSMA_CANCEL;
2243         else
2244                 return -1;
2245 }
2246
2247 static ssize_t
2248 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2249                             size_t user_count, __u64 *mask)
2250 {
2251         char *buf, *pos, *name;
2252         size_t buf_size;
2253         __u64 new_mask = 0;
2254         int rc;
2255         ENTRY;
2256
2257         if (!(user_count < 4096))
2258                 RETURN(-ENOMEM);
2259
2260         buf_size = user_count + 1;
2261
2262         OBD_ALLOC(buf, buf_size);
2263         if (buf == NULL)
2264                 RETURN(-ENOMEM);
2265
2266         if (copy_from_user(buf, user_buf, buf_size - 1))
2267                 GOTO(out, rc = -EFAULT);
2268
2269         buf[buf_size - 1] = '\0';
2270
2271         pos = buf;
2272         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2273                 int action;
2274
2275                 if (*name == '\0')
2276                         continue;
2277
2278                 action = hsm_copytool_name2action(name);
2279                 if (action < 0)
2280                         GOTO(out, rc = -EINVAL);
2281
2282                 new_mask |= (1UL << action);
2283         }
2284
2285         *mask = new_mask;
2286         rc = user_count;
2287 out:
2288         OBD_FREE(buf, buf_size);
2289
2290         RETURN(rc);
2291 }
2292
2293 static ssize_t
2294 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2295                                         size_t count, loff_t *off)
2296 {
2297         struct seq_file         *m = file->private_data;
2298         struct mdt_device       *mdt = m->private;
2299         struct coordinator *cdt = &mdt->mdt_coordinator;
2300
2301         return mdt_write_hsm_request_mask(file, buf, count,
2302                                            &cdt->cdt_user_request_mask);
2303 }
2304
2305 static ssize_t
2306 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2307                                         size_t count, loff_t *off)
2308 {
2309         struct seq_file         *m = file->private_data;
2310         struct mdt_device       *mdt = m->private;
2311         struct coordinator      *cdt = &mdt->mdt_coordinator;
2312
2313         return mdt_write_hsm_request_mask(file, buf, count,
2314                                            &cdt->cdt_group_request_mask);
2315 }
2316
2317 static ssize_t
2318 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2319                                         size_t count, loff_t *off)
2320 {
2321         struct seq_file         *m = file->private_data;
2322         struct mdt_device       *mdt = m->private;
2323         struct coordinator      *cdt = &mdt->mdt_coordinator;
2324
2325         return mdt_write_hsm_request_mask(file, buf, count,
2326                                            &cdt->cdt_other_request_mask);
2327 }
2328
2329 static int mdt_hsm_cdt_raolu_seq_show(struct seq_file *m, void *data)
2330 {
2331         struct mdt_device *mdt = m->private;
2332         struct coordinator *cdt = &mdt->mdt_coordinator;
2333         ENTRY;
2334
2335         seq_printf(m, "%d\n", (int)cdt->cdt_remove_archive_on_last_unlink);
2336         RETURN(0);
2337 }
2338
2339 static ssize_t
2340 mdt_hsm_cdt_raolu_seq_write(struct file *file, const char __user *buffer,
2341                             size_t count, loff_t *off)
2342
2343 {
2344         struct seq_file *m = file->private_data;
2345         struct mdt_device *mdt = m->private;
2346         struct coordinator *cdt = &mdt->mdt_coordinator;
2347         __s64 val;
2348         int rc;
2349         ENTRY;
2350
2351         rc = lprocfs_str_to_s64(buffer, count, &val);
2352         if (rc < 0)
2353                 RETURN(rc);
2354
2355         cdt->cdt_remove_archive_on_last_unlink = val;
2356         RETURN(count);
2357 }
2358
2359 LPROC_SEQ_FOPS(mdt_hsm_cdt_loop_period);
2360 LPROC_SEQ_FOPS(mdt_hsm_cdt_grace_delay);
2361 LPROC_SEQ_FOPS(mdt_hsm_cdt_active_req_timeout);
2362 LPROC_SEQ_FOPS(mdt_hsm_cdt_max_requests);
2363 LPROC_SEQ_FOPS(mdt_hsm_cdt_default_archive_id);
2364 LPROC_SEQ_FOPS(mdt_hsm_user_request_mask);
2365 LPROC_SEQ_FOPS(mdt_hsm_group_request_mask);
2366 LPROC_SEQ_FOPS(mdt_hsm_other_request_mask);
2367 LPROC_SEQ_FOPS(mdt_hsm_cdt_raolu);
2368
2369 /* Read-only proc files for request counters */
2370 static int mdt_hsm_cdt_archive_count_seq_show(struct seq_file *m, void *data)
2371 {
2372         struct mdt_device *mdt = m->private;
2373         struct coordinator *cdt = &mdt->mdt_coordinator;
2374         ENTRY;
2375
2376         seq_printf(m, "%d\n", atomic_read(&cdt->cdt_archive_count));
2377         RETURN(0);
2378 }
2379
2380 static int mdt_hsm_cdt_restore_count_seq_show(struct seq_file *m, void *data)
2381 {
2382         struct mdt_device *mdt = m->private;
2383         struct coordinator *cdt = &mdt->mdt_coordinator;
2384         ENTRY;
2385
2386         seq_printf(m, "%d\n", atomic_read(&cdt->cdt_restore_count));
2387         RETURN(0);
2388 }
2389
2390 static int mdt_hsm_cdt_remove_count_seq_show(struct seq_file *m, void *data)
2391 {
2392         struct mdt_device *mdt = m->private;
2393         struct coordinator *cdt = &mdt->mdt_coordinator;
2394         ENTRY;
2395
2396         seq_printf(m, "%d\n", atomic_read(&cdt->cdt_remove_count));
2397         RETURN(0);
2398 }
2399
2400 LPROC_SEQ_FOPS_RO(mdt_hsm_cdt_archive_count);
2401 LPROC_SEQ_FOPS_RO(mdt_hsm_cdt_restore_count);
2402 LPROC_SEQ_FOPS_RO(mdt_hsm_cdt_remove_count);
2403
2404 static struct lprocfs_vars lprocfs_mdt_hsm_vars[] = {
2405         { .name =       "agents",
2406           .fops =       &mdt_hsm_agent_fops                     },
2407         { .name =       "actions",
2408           .fops =       &mdt_hsm_actions_fops,
2409           .proc_mode =  0444                                    },
2410         { .name =       "default_archive_id",
2411           .fops =       &mdt_hsm_cdt_default_archive_id_fops    },
2412         { .name =       "grace_delay",
2413           .fops =       &mdt_hsm_cdt_grace_delay_fops           },
2414         { .name =       "loop_period",
2415           .fops =       &mdt_hsm_cdt_loop_period_fops           },
2416         { .name =       "max_requests",
2417           .fops =       &mdt_hsm_cdt_max_requests_fops          },
2418         { .name =       "policy",
2419           .fops =       &mdt_hsm_policy_fops                    },
2420         { .name =       "active_request_timeout",
2421           .fops =       &mdt_hsm_cdt_active_req_timeout_fops    },
2422         { .name =       "active_requests",
2423           .fops =       &mdt_hsm_active_requests_fops           },
2424         { .name =       "user_request_mask",
2425           .fops =       &mdt_hsm_user_request_mask_fops,        },
2426         { .name =       "group_request_mask",
2427           .fops =       &mdt_hsm_group_request_mask_fops,       },
2428         { .name =       "other_request_mask",
2429           .fops =       &mdt_hsm_other_request_mask_fops,       },
2430         { .name =       "remove_archive_on_last_unlink",
2431           .fops =       &mdt_hsm_cdt_raolu_fops,                },
2432         { .name =       "archive_count",
2433           .fops =       &mdt_hsm_cdt_archive_count_fops,        },
2434         { .name =       "restore_count",
2435           .fops =       &mdt_hsm_cdt_restore_count_fops,        },
2436         { .name =       "remove_count",
2437           .fops =       &mdt_hsm_cdt_remove_count_fops,         },
2438         { 0 }
2439 };