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